FreeCad Tutorial

Must Watch!



MustWatch

download FreeCad
FreeCAD Tutorial for Beginners Booleans Assembly Sketch Export Part Design
Learn FreeCAD


Manual:Introduction

FreeCAD is a free, open source parametric 3D modeling application. It is made primarily to model real-world objects, ranging from small electronic components up to large objects such as buildings and civil engineering projects, with a strong focus on 3D-printable objects. FreeCAD is free to download, use, distribute and modify, and its source code is open and published under the very permissive LGPL license. The data you produce with FreeCAD is fully yours, and can be recovered without FreeCAD. FreeCAD is also fundamentally a social project, as it is developed and maintained by a community of developers and users united by their passion for FreeCAD. This manual is an experiment, taking a different approach from the official FreeCAD documentation wiki. The wiki is written collaboratively by dozens of community members. Like most wikis, it contains huge amounts of information but is somewhat difficult to access and navigate by newcomers. This makes it an excellent resource for reference, but a less practical tool for learning FreeCAD. This manual will walk you through much of the information available on the wiki, but we hope the step-by-step approach based on examples and a more unified tone due to a smaller number of authors will make it more suitable for a first contact with FreeCAD. It will become a companion for the wiki, but not replace it. This manual is being written for the newest stable version of FreeCAD, version 0.18 (early 2019). The contents of this manual are published under the Creative Commons 4.0 license, and can be freely used, downloaded, copied, and modified. The source files for this manual are hosted on this wiki, and on the original github account used to write the first version of this book. Easier to read HTML, PDF, MOBI and EPUB versions are available on GitBook. A printed version is being prepared.


Manual:What is FreeCAD

FreeCAD is not designed for a particular kind of work, or for making a particular kind of object. Instead, it permits users to produce models of objects of widely differing sizes for many purposes, from small electronic components to 3D-printable pieces all the way up to buildings. Each of these tasks has different dedicated sets of tools and workflows available. FreeCAD is also multiplatform (it runs exactly the same way on Windows, Mac OS and Linux platforms), and it is open source. Being open source, FreeCAD benefits from the contributions and efforts of a large community of programmers, enthusiasts and users worldwide. FreeCAD is essentially an application built by the people who use it, instead of being made by a company trying to sell you a product. It also means that FreeCAD is free, not only to use, but also to distribute, copy, modify, or even sell. FreeCAD benefits from the huge, accumulated experience of the open source world. Internally, it includes several other open source components, and FreeCAD itself can be used as a component in other applications. It possesses many features that have become standard in the open source world, such as supporting a wide range of file formats, and being scriptable, customizable and modifiable. All made possible through a dynamic and enthusiastic community of users. The official website of FreeCAD is at http://www.freecadweb.org


Manual:Installing

The official FreeCAD download page for Windows and Mac OS is https://github.com/FreeCAD/FreeCAD/releases FreeCAD versions The official releases of FreeCAD, that you can find on the page referenced above and in your distribution's software manager, are stable versions. However, the development of FreeCAD is fast! New features and bug fixes are added almost every single day. Since it is often a long time between stable releases, you might be interested in trying a more bleeding-edge version of FreeCAD. These development versions, or pre-releases, are uploaded from time to time to the download page mentioned above, or, if you are using Ubuntu or Fedora, the FreeCAD community also maintains PPA (Personal Package Archives) and copr 'daily builds' which are regularly updated with the most recent changes. If you are installing FreeCAD in a virtual machine, please be aware that the performance might be poor (in some cases unusable) due to the limits of OpenGL support on most virtual machines.

Installing on Windows

Download an installer (.exe) package corresponding to your version of Windows (32bit or 64bit) from the download page. The FreeCAD installers should work on any windows version starting from Windows 7. Double-click the downloaded installer. Accept the terms of the LGPL license, this will be one of the few cases where you can really, safely click the "accept" button without reading the text. No hidden clauses: You can leave the default path here, or change if you wish: No need to set the PYTHONPATH variable, unless you plan to do some advanced python programming, in which case you probably already know what this is for: During the installation, a couple of additional components, which are bundled inside the installer, will be installed too: That's it, FreeCAD is installed. You will find it in your start menu. Installing a development version Packaging FreeCAD and creating an installer takes some time and dedication, so usually development (also called pre-release) versions are provided as .zip (or .7z) archives. These don't need to be installed; just unpack them and launch FreeCAD by double-clicking the FreeCAD.exe file that you will find inside. This also allows you to keep both the stable and "unstable" versions together on the same computer.

Uninstalling

Hopefully you won't want to uninstall FreeCAD, but it is good to know how. On Windows and Linux, uninstalling FreeCAD is very straightforward. On Windows, use the standard "remove software" option found in the control panel; on Linux, remove it with the same software manager you used to install it. On Mac OS, simply remove it from the Applications folder.

Setting basic preferences

Once FreeCAD is installed, you might want to open it and change some preferences. Preference settings in FreeCAD are located under menu Edit → Preferences. Listed below are some basic settings you may wish to change; you can browse through the preference pages to see if there is anything else you want to change. Language: (General category, General tab) FreeCAD will automatically pick the language of your operating system, but you might want to change that. FreeCAD is almost fully translated into five or six languages; others are currently only partially translated. You can easily help translating FreeCAD. Auto-load module: (General category, General tab) Normally, FreeCAD will start by showing you the start page. You can skip this and begin a FreeCAD session directly in the workbench of your choice, listed under Startup, Auto load module after startup. Workbenches will be explained in detail in the next chapter. Create new document at startup: (General category, Document tab) Combined with the Auto-load module option above, if checked this starts FreeCAD ready for work. Storage options: (General category, Document tab) As with any complex application, FreeCAD likely contains bugs causing it to crash occasionally. Here you can configure options to help you to recover your work in case of a crash. Authoring and license: (General category, Document tab) Here you set the values to be used for new files you create. Consider making your files shareable right from the start, by using a friendlier, copyleft license like Creative Commons. Redirect internal python messages: (General category, Output window tab) These two options are always good to check, as they will cause messages from the internal python interpreter to show up in the Report View when there's a problem running a python script. Units: (General category, Units tab) Here you can set the default units system you wish to use. Zoom at cursor: (Display category, 3D tab) If set, zoom operations will be focused at the mouse pointer. If unset, the center of the current view is the zoom focus. Invert zoom: (Display category, 3D tab) Inverts the direction of zooming relative to mouse movement.

Installing additional content

As the FreeCAD project and its community grows quickly, and also because it is easy to extend, external contributions and side-projects made by community members and other enthusiasts begin to appear everywhere on the internet. Most of these external projects are workbenches or macros, and can be easily installed right from within FreeCAD via the Addon Manager located under menu Tools. The addons manager will allow you to install many interesting components, for example: A Parts library, which contains all kinds of useful models, or pieces of models, created by FreeCAD users that can be freely used in your projects. The library can be used and accessed right from inside your FreeCAD installation. Additional workbenches, that extend the functionality of FreeCAD for certain tasks, for example animate parts of your models, or areas, such as sheet metal folding or BIM. Further explanations of each workbench and what tools it contains is given on each addon page, that you can visit by clicking the corresponding link on the addon manager. A collection of macros, which are also available on the FreeCAD wiki along with documentation about how to use them. If you are using the Ubuntu operating system, some of the addons above are also available as packages on the FreeCAD addons PPA Read more More download options FreeCAD PPA for Ubuntu FreeCAD addons PPA for Ubuntu Compile FreeCAD yourself FreeCAD translations FreeCAD github page The FreeCAD addons manager


Manual:The FreeCAD Interface

The start center is a convenient "welcome screen", that shows useful information for newcomers, like the latest files you have been working on, what's new in the FreeCAD world, or quick info about the most common Workbenches. It will also notify you if a new stable version of FreeCAD is available. After a while, when you are more familiar with FreeCAD, you may have made changes in the preferences so when FreeCAD starts you find yourself directly in one of the Workbenches with a new document open. Or, simply close the start page tab and create a new document:

Workbenches

Note that some of the icons have changed between the two screencaptures above. This is where the most important concept used in the FreeCAD interface comes into play: Workbenches. Workbenches are groups of tools (toolbar buttons, menus, and other interface controls) that are grouped together by specialty. Think of a workshop where you have different people working together: A person who works with metal, another with wood. Each of them has, in their workshop, a separate table with specific tools for his/her job. However, they can all work on the same objects. The same happens in FreeCAD. The most important control of the FreeCAD interface is the Workbench selector, which you use to switch from one Workbench to the other: The Workbenches often confuse new users, since it's not always easy to know in which Workbench to look for a specific tool. But they are quick to learn, and after a short while it will feel natural -- realizing it is a convenient way to organize the multitude of tools FreeCAD has to offer. Workbenches are also fully customizable (see below). The same tool may appear in more than one workbench. The button icon for a particular tool will always be the same no matter which workbench it appears in. Later in this manual, you will also find a table showing the contents of all Workbenches.

The interface

Let's have a better look at the different parts of the interface: The 3D view is the main component of the interface; it is where the objects you are working with are drawn and manipulated. You may have several views of the same document (or same objects), or several documents open at the same time. Each of these views may be individually undocked from the main window. You may select objects or parts of objects by clicking them, and you can pan, zoom and rotate the view with the mouse buttons. This will be explained further in the next chapter. In addition to the 3D view panel, the following information panels are available. They may be made visible or hidden by selecting them from View → Panels . The name of the panel appears in the upper left corner of the panel when it is displayed: The combo view has two tabs: The Model tab shows you the contents and structure of your document above and the properties (or parameters) of the selected object(s) below. These properties are separated into two categories: Data (properties which concern the geometry itself) View (properties that affect how the geometry looks on screen). The Tasks tab is where FreeCAD will prompt you for values specific to the workbench and tool you are currently using. For example, entering a 'length' value when the Draft Workbench Line Tool is being used. It will clear and switch back to the Model tab after the OK (or Cancel) button is pressed. Double-clicking the related object in the Model tab will usually reopen the corresponding Task tab in order to modify the settings. The Tasks tab sometimes has puzzling and frustrating side-effects. If the Task tab is not empty, some FreeCAD operations will not work as expected. For example, if you have a single object in your model such as a cube, double-clicking on it will open the Tasks tab to allow you to modify the parameters characterizing the cube. If you have the Selection view open, you will see the cube's internal name listed there. The entire cube will turn green in the 3D panel, indicating the entire cube is selected. Clicking on the background will deselect the entire cube and clear the Selection view. So far, this is normal behavior. However, if you now click on a face of the cube, instead of that face being selected, nothing will be selected — because the Tasks tab has not been completed. Even if you have made no modifications to the parameters there, FreeCAD is waiting for the OK (or other) button in the Tasks tab to be clicked. The report view is normally hidden, but it is a good idea to open it as it will list any information, warnings or errors to help you decipher (or debug) what you may have done wrong. The Python console is also hidden by default. This is where you can interact with the contents of the document using the Python language. Since every action you do on the FreeCAD interface actually executes a piece of Python code, having this open allows you to watch the code unfold in real time — allowing you a wonderful and easy way to learn a little Python on the way, almost without noticing it. The tree view displays only the object tree shown under the Model tab in the combo view. It is normally hidden. The property view displays only the object property information shown at the bottom of the combo view. It is normally hidden. The selection view shows the names of any objects which are currently selected. These are the objects to which a workbench operation will be applied. It can be used to refine the selection by deselecting some of those objects before a workbench operation is applied. The selection view can also be used to search for objects by name and then select them. By default, the selection view is hidden. While you can often determine the currently selected object(s) by looking at the object tree in the Model tab of the combo view, for complex operations requiring multiple selections and where selection is difficult it is helpful to make this view visible so you can both see the labels and count the selected objects.

Customizing the interface

The interface of FreeCAD is highly customizable. All panels and toolbars can be moved to different places or stacked one above another. They can also be closed and reopened when needed from the View menu or by right-clicking on an empty area of the interface. There are, however, many more options available, such as creating custom toolbars with tools from any of the Workbenches, or assigning and changing keyboard shortcuts. These advanced customization options are available from the Tools → Customize menu: Read more Getting started with FreeCAD Customizing the interface Workbenches More about Python


Manual:Navigating in the 3D view

The FreeCAD 3D space is a Euclidean space. It has an origin point and three axes: X, Y and Z. If you look at your scene from above, conventionally, the X axis points to the right, the Y axis to the back, and the Z axis upwards. In the lower right corner of the FreeCAD view, you can always see from where you are viewing the scene: The point where the three axes meet is the origin. It is the point where the value of all coordinates is zero. For any given axis, moving in one direction will increase the coordinate value and moving in the opposite direction will decrease the coordinate value. Every point of every object that exists in the 3D space can be located by its (x,y,z) coordinates. For example, a point with coordinates (2,3,1) will lie at +2 units on the X axis, +3 units on the Y axis, and +1 unit on the Z axis: You can look at that scene from any angle, as if you were holding a camera. That camera can be moved left, right, up and down (pan), rotated around what it is pointing at (rotate) and brought closer to or further from the scene (zoom).

The FreeCAD 3D view

Mouse Navigation

Navigating in the FreeCAD 3D view can be done with a mouse, a Space Navigator device, the keyboard, a touchpad, or a combination of those. FreeCAD implements several navigation modes, which determine how the three basic view manipulation operations (pan, rotate and zoom) are done, as well as how selection of objects on the screen is performed. Navigation modes are accessed from the Preferences screen, or directly by right-clicking anywhere on the 3D view: Each of these modes allocates different mouse buttons, or mouse + keyboard combinations, or mouse gestures, to these four operations. The following table shows the principal available modes:
ModePanRotateZoomSelect
OpenInventor Hold Ctrl + drag
CAD (default) or or or
BlenderHold Shift + drag or drag
TouchpadHold Shift + drag Alt + PgUp / PgDn
Gesturedrag drag
OpenCascade

Keyboard Navigation

Alternatively, some keyboard controls are always available, no matter the navigation mode: Ctrl + and Ctrl + to zoom in and out, respectively. The arrow keys, , to shift the view left/right and up/down Shift + and Shift + to rotate the view by 90 degrees The numeric keys, , for the seven standard views: Isometric, Front, Top, Right, Rear, Bottom, and Left VO will set the camera in Orthographic view. While VP sets it in Perspective view. Ctrl will allow you to select more than one object or element These controls are also available from the View menu and some from the View toolbar.

Using the Navigation Cluster

In the default setup, there is a Navigation Cluster in the upper right corner of the 3D display. This may be used to rotate the displayed object by a fixed amount, reset the display to one of several standard views, and change the display mode. When using the navigation cluster, a control point will turn light blue when the pointer is hovering over a sensitive area. If the area below the pointer does not change color, clicking on it will have no affect. As of this writing (v0.18), there are some registration issues which prevent all parts of some control points from being active. Clicking on a face will switch the view to that face; clicking on a corner will switch to a view with that corner pointing towards you. Clicking one of the four triangles will rotate the view 45 degrees in the indicated direction. Clicking one of the two curved arrows at the top will rotate the view 45 degrees in the indicated direction around a line pointing towards you. The navigation cluster may be moved to any part of the 3D display by dragging. The drag (left) mouse button must be pressed inside the cube itself to initiate a drag. The structure will not begin moving until the pointer is dragged outside the cube. There is a smaller mini-cube in the lower right of the cluster which activates a drop-down menu allowing you to switch the viewing mode.

Selecting objects

Objects in the 3D view can be selected by clicking them with the corresponding mouse button, depending on the navigation mode (described above). A single click will select the object and one of its subcomponents (edge, face, vertex). Double-clicking will select the object and all its subcomponents. You can select more than one subcomponent, or even different subcomponents from different objects, by pressing the CTRL key. Clicking with the selection button on an empty portion of the 3D view will deselect everything. A panel called "Selection view", available from the View menu, can also be turned on, which shows you what is currently selected: You can also use the Selection View to select objects by searching for a particular object. Read more The FreeCAD navigation modes Navigation Cluster


Manual:The FreeCAD document

Inside the document, the objects can be moved into groups, and have a unique name. Managing groups, objects and object names is done mainly from the Tree view. There, you can create groups, move objects to groups, delete objects or groups. By right-clicking in the tree view or on an object, you can rename objects, change their color, hide or show them, or possibly other operations, depending on the current workbench. The objects inside a FreeCAD document can be of different types. Each workbench can add its own types of objects, for example the Mesh Workbench adds mesh objects, the Part Workbench adds Part objects, etc. If there is at least one document open in FreeCAD, there is always one and only one active document. That's the document that appears in the current 3D view, the document you are currently working on. If you switch tabs to another document, that one becomes the active document. Most operations always work on the active document. FreeCAD documents are saved with the .FcStd extension, which is a zip-based compound format, similar to LibreOffice. If something goes very wrong, it is often possible to unzip it and fix the problem or rescue the data. Read more The FreeCAD document File Format FCStd


Manual:Parametric objects

This last type allows to quickly build complex chains of operations, each new object being based on a previous one, and adding new features to it. In the example below, a solid, cubic object (Pad) is based on a rectangular 2D shape (Sketch) and has an extrusion distance. With these two properties, it produces a solid shape by extruding the base shape by the given distance. You can then use this object as a base for further operations, such as drawing a new 2D shape on one of its faces (Sketch001) and then making a subtraction (Pocket), until arriving at your final object. All the intermediary operations (2D shapes, pad, pocket, etc) are still there, and you can still change any of their parameters anytime. The whole chain will be rebuilt (recomputed) whenever needed. Two important things are necessary to know: Recomputation is not always automatic. Heavy operations, that might modify a big portion of your document, and therefore take some time, are not performed automatically. Instead, the object (and all the objects that depend on it) will be marked for recomputation (a small blue icon appears on them in the tree view). You must then press the recompute button (or Edit->Refresh) to have all the marked objects recomputed. The dependency tree must always flow in the same direction. Loops are forbidden. (See DAG, and DAG view) You can have object A which depends on object B which depend on object C. But you cannot have object A which depends on object B which depends on object A. That would be a circular dependency. However, you can have many objects that depend on the same object, for example objects B and C both depend on A. Menu Tools -> Dependency graph shows you a dependency diagram like on the image above. It can be useful to detect problems. Not all objects are parametric in FreeCAD. Often, the geometry that you import from other files won't contain any parameter, and will be simple, non-parametric objects. However, these can often be used as a base, or starting point for newly created parametric objects, depending, of course, on what the parametric object requires and the quality of the imported geometry. All objects, however, parametric or not, will have a couple of basic parameters, such as a Name, which is unique in the document and cannot be edited, a Label, which is a user-defined name that can be edited, and a placement, which holds its position in the 3D space. Finally, it is worth noting that custom parametric objects are easy to program in python. Read more The properties editor How to program parametric objects Positioning objects in FreeCAD Enabling the dependency graph


Manual:Import and export to other filetypes

FormatImportExportNotes
STEPYesYesThis is the most faithful import/export format available, since it supports solid geometry and NURBS. Use it whenever it is possible.
IGESYesYesAn older solid format, also very well supported. Some older applications don't support STEP but have IGES.
BREPYesYesThe native format of OpenCasCade, FreeCAD's geometry kernel.
DXFYesYesAn open format maintained by Autodesk. Since the 3D data inside a DXF file is encoded in proprietary format, FreeCAD can only import/export 2D data to/from this format.
DWGYesYesThe proprietary version of DXF. Requires the installation of the Teigha File Converter utility. This format suffers from the same limitations as DXF.
OBJYesYesA mesh-based format. Can only contain triangulated meshes. All solid and NURBS-based objects of FreeCAD will be converted to mesh on export. An alternative exporter is provided by the Arch workbench, more suited to the export of architectural models.
DAEYesYesThe main import/export format of Sketchup. Can only contain triangulated meshes. All solid and NURBS-based objects of FreeCAD will be converted to mesh on export.
STLYesYesA mesh-based format, commonly used for 3D printing. Can only contain triangulated meshes. All solid and NURBS-based objects of FreeCAD will be converted to mesh on export.
PLYYesYesAn older mesh-based format. Can only contain triangulated meshes. All solid and NURBS-based objects of FreeCAD will be converted to mesh on export.
IFCYesYesIndustry Foundation Classes. Requires the installation of IfcOpenShell-python. The IFC format and its compatibility with other applications is a complex affair, use with care.
SVGYesYesAn excellent, widespread 2D graphics format
VRMLYesYesA rather old mesh-based web format.
GCODEYesYesFreeCAD can already import and export to/from several flavors of GCode, but only a small number of machines is supported at the moment.
CSGYesNoOpenSCAD's CSG (Constructive Solid Geometry) format.
Some of these file formats have options. These can be configured from menu Edit → Preferences → Import/export: Read more All file formats supported by FreeCAD Working with DXF files in FreeCAD: Enabling DXF and DWG support Working with SVG files in FreeCAD Importing and exporting to IFC OpenCasCade Teigha File Converter IFC Specifications Database IfcOpenShell


Manual:All workbenches at a glance

1 Part 2 Draft 3 Sketcher 4 Part Design 5 Arch 6 Drawing 7 Other built-in workbenches 8 External workbenches

Part

The Part Workbench provides basic tools for working with solid parts: primitives, such as cubes and spheres, and simple geometric operations and boolean operations. Being the main anchor point with OpenCasCade, the Part workbench provides the foundation of FreeCAD's geometry system, and almost all other workbenches produce Part-based geometry.
ToolDescriptionToolDescription
BoxDraws a box ConeDraws a cone
CylinderDraws a cylinder SphereDraws a sphere
TorusDraws a torus (ring) Create primitivesCreates various other parametric geometric primitives
Shape builderCreate more complex shapes from primitives UnionFuses (unions) two objects
CommonExtracts the common (intersection) part of two objects CutCuts (subtracts) one object from another
JoinConnectConnects interiors of walled objects JoinEmbedEmbeds a walled object into another walled object
JoinCutoutCreates a cutout in a wall of an object for another walled object ExtrudeExtrudes planar faces of an object
FilletFillets (rounds) edges of an object RevolveCreates a solid by revolving another object (not solid) around an axis
SectionCreates a section by intersecting an object with a section plane CrossSectionsCreates multiple cross sections along an object
ChamferChamfers edges of an object MirrorMirrors the selected object on a given mirror plane
Ruled SurfaceCreate a ruled surface between selected curves SweepSweeps one or more profiles along a path
Part_LoftLofts from one profile to another OffsetCreates a scaled copy of the original object
ThicknessAssign a thickness to the faces of a shape

Draft

The Draft Workbench provides tools to do basic 2D CAD drafting tasks: lines, circles, etc... and a series of generic handy tools such as move, rotate or scale. It also provides several drawing aids, such as grid and snapping. It is principally meant to draw the guidelines for Arch objects, but also serves as FreeCAD's "swiss knife".
ToolDescriptionToolDescription
LineDraws a line segment between 2 points WireDraws a line made of multiple line segments (polyline)
CircleDraws a circle from center and radius ArcDraws an arc segment from center, radius, start angle and end angle
EllipseDraws an ellipse from two corner points PolygonDraws a regular polygon from a center and a radius
RectangleDraws a rectangle from 2 opposite points TextDraws a multi-line text annotation
DimensionDraws a dimension annotation BSplineDraws a B-Spline from a series of points
PointInserts a single point ShapestringThe ShapeString tool inserts a compound shape representing a text string at a given point in the current document
FacebinderCreates a new object from selected faces on existing objects Bezier CurveDraws a Bezier curve from a series of points
MoveMoves or copies objects from one location to another RotateRotates objects by a certain angle around a point
OffsetOffsets an object to a certain distance TrimexTrims, extends or extrudes an object
UpgradeTurns or joins objects into a higher-level object DowngradeTurns or separates objects into lower-level objects
ScaleScales objects in relation to a point Shape 2D ViewCreates a 2D object which is a flattened view of another object
Draft to SketchConverts a Draft object to a Sketch and vice-versa ArrayCreates a rectangular array from an object
CloneCreates linked copies of objects MirrorMirrors objects across a line

Sketcher

The Sketcher Workbench contains tools to build and edit complex 2D objects, called sketches. The geometry inside these sketches can be precisely positioned and relationed by the use of constraints. They are primarily meant to be the building blocks of PartDesign geometry, but are useful everywhere in FreeCAD.
ToolDescriptionToolDescription
PointDraws a point LineDraws a line segment from 2 points
ArcDraws an arc segment from center, radius, start angle and end angle Arc 3 pointsDraws an arc segment from two endpoints and another point on the circumference
CircleDraws a circle from center and radius Circle 3 pointsDraws a circle from three points on the circumference
EllipseDraws an ellipse by center point, major radius point and minor radius point Ellipse 3 pointsDraws an ellipse by major diameter (2 points) and minor radius point
Arc of ellipseDraws an arc of ellipse by center point, major radius point, starting point and ending point PolylineDraws a line made of multiple line segments. Several drawing modes available
RectangleDraws a rectangle from 2 opposite points TriangleDraws a regular triangle inscribed in a construction geometry circle
SquareDraws a regular square inscribed in a construction geometry circle PentagonDraws a regular pentagon inscribed in a construction geometry circle
HexagonDraws a regular hexagon inscribed in a construction geometry circle HeptagonDraws a regular heptagon inscribed in a construction geometry circle
OctagonDraws a regular octagon inscribed in a construction geometry circle SlotDraws an oval by selecting the center of one semicircle and an endpoint of the other semicircle
FilletMakes a fillet between two lines joined at one point TrimmingTrims a line, circle or arc with respect to a clicked point
External geometryCreates an edge linked to external geometry Construction modeToggles an element to/from construction mode. A construction object will not be used in a 3D geometry operation and is only visible while editing the Sketch that contains it
CoincidentAffixes a point onto (coincident with) one or more other points. Point on objectAffixes a point onto another object such as a line, arc, or axis.
VerticalConstrains the selected lines or polyline elements to a true vertical orientation. More than one object can be selected before applying this constraint. HorizontalConstrains the selected lines or polyline elements to a true horizontal orientation. More than one object can be selected before applying this constraint.
ParallelConstrains two or more lines parallel to one another. PerpendicularConstrains two lines perpendicular to one another, or constrains a line perpendicular to an arc endpoint.
TangentCreates a tangent constraint between two selected entities, or a co-linear constraint between two line segments. Equal lengthConstrains two selected entities equal to one another. If used on circles or arcs their radii will be set equal.
SymmetricConstrains two points symmetrically about a line, or constrains the first two selected points symmetrically about a third selected point. LockConstrains the selected item by setting vertical and horizontal distances relative to the origin, thereby locking the location of that item
Horizontal distanceFixes the horizontal distance between two points or line endpoints. If only one item is selected, the distance is set to the origin. Vertical distanceFixes the vertical distance between 2 points or line endpoints. If only one item is selected, the distance is set to the origin.
DistanceDefines the distance of a selected line by constraining its length, or defines the distance between two points by constraining the distance between them. RadiusDefines the radius of a selected arc or circle by constraining the radius.
Internal angleDefines the internal angle between two selected lines. Snell's lawConstrains two lines to obey a refraction law to simulate the light going through an interface
Internal alignmentAligns selected elements to selected shape (e.g. a line to become major axis of an ellipse) Map sketchMaps a sketch to the previously selected face of a solid
MergeMerge two or more sketches MirrorMirrors selected elements of a sketch

Part Design

The Part Design Workbench contains advanced tools to build solid parts. It also contains all the tools from the sketcher. Since it can only produce solid shapes (the rule number one of Part Design), it is the main workbench to use when designing pieces (parts) to be manufactured or 3D-printed, as you will always obtain a printable object.
ToolDescriptionToolDescription
PadExtrudes a solid object from a selected sketch PocketCreates a pocket from a selected sketch. The sketch must be mapped to an existing solid object's face
RevolutionCreates a solid by revolving a sketch around an axis GrooveCreates a groove by revolving a sketch around an axis
FilletFillets (rounds) edges of an object ChamferChamfers edges of an object
DraftApplies angular draft to faces of an object MirroredMirrors features on a plane or face
Linear patternCreates a linear pattern of features Polar patternCreates a polar pattern of features
ScaledScales features to a different size MultitransformAllows creating a pattern with any combination of the other transformations
Shaft wizardGenerates a shaft from a table of values and allows to analyze forces and moments Involute gear wizardAllows you to create several types of gears

Arch

The Arch Workbench contains tools to work with BIM projects (civil engineering and architecture). It also contains all the tools from the Draft workbench. The main use of the Arch Workbench is to create BIM objects or give BIM attributes to objects built with other workbenches, in order to export them to IFC.
ToolDescriptionToolDescription
WallCreates a wall from scratch or using a selected object as a base StructureCreates a structural element from scratch or using a selected object as a base
RebarCreates a reinforcement bar in a selected structural element FloorCreates a floor including selected objects
BuildingCreates a building including selected objects SiteCreates a site including selected objects
WindowCreates a window using a selected object as a base Section planeAdds a section plane object to the document
AxisAdds an axes system to the document RoofCreates a sloped roof from a selected face
SpaceCreates a space object in the document StairsCreates a stairs object in the document
PanelCreates a panel object from a selected 2D object FrameCreates a frame object from a selected layout
EquipmentCreates an equipment or furniture object MaterialAttributes a material to selected objects
ScheduleCreates different types of schedules Cut planeCut an object according to a plan
AddAdds objects to a component RemoveSubtracts or removes objects from a component
SurveyEnters or leaves surveying mode

Drawing

The Drawing Workbench handles the creation and manipulation of 2D drawing sheets, used for displaying views of your 3D work in 2D. These sheets can then be exported to 2D applications in SVG or DXF formats, to a PDF file or printed.
ToolDescriptionToolDescription
New sheetCreates a new drawing sheet ViewInserts a view of the selected object in the active drawing sheet
AnnotationAdds an annotation to the current drawing sheet ClipAdds a clip group to the current drawing sheet
Open browserOpens a preview of the current sheet in the browser Ortho viewsAutomatically creates orthographic views of an object on the current drawing sheet
SymbolAdds the contents of a SVG file as a symbol on the current drawing sheet Draft viewInserts a special Draft view of the selected object in the current drawing sheet
SaveSaves the current sheet as a SVG file

Other built-in workbenches

Although the above summarizes the most important tools of FreeCAD, many more workbenches are available, among them: The Mesh Workbench allows to work with polygon meshes. Although meshes are not the preferred type of geometry to work with in FreeCAD, because of their lack of precision and support for curves, meshes still have a lot of uses, and are fully supported in FreeCAD. The Mesh Workbench also offers a number of Part-to-Mesh and Mesh-to-Part tools. The Raytracing Workbench offers tools to interface with external renderers such as povray or luxrender. Right from inside FreeCAD, this workbench allows you to produce high-quality renderings from your models. The Spreadsheet Workbench permits the creation and manipulation of spreadsheet data, that can be extracted from FreeCAD models. Spreadsheet cells can also be referenced in many areas of FreeCAD, allowing to use them as master data structures. The FEM Workbench deals with Finite Elements Analysis, and permits the performing of pre- and post-processing FEM calculations and to display the results graphically.

External workbenches

A number of other very useful workbenches produced by FreeCAD community members also exist. Although they are not included in a standard FreeCAD installation,they are easy to install as plug-ins. They are all referenced in the FreeCAD-addons repository. Among the most developed are: The Drawing Dimensioning Workbench offers many new tools to work directly on Drawing Sheets and allow you to add dimensions, annotations and other technical symbols with great control over their aspect. The Drawing Dimensioning Workbench is no longer maintained. The Fasteners Workbench offers a wide range of ready-to-insert fasteners objects like screws, bolts, rods, washers and nuts. Many options and settings are available. The A2plus workbench offers a series of tools to mount and work with assemblies. Read more The complete list of workbenches The Part Workbench The Draft Workbench The Sketcher and Part Design Workbench The Arch Workbench The TechDraw Workbench The FEM Workbench The FreeCAD-addons repository


Manual:Traditional modeling, the CSG way

The difference between the two can be compared to the difference between bitmap and vector images. As with bitmap images, polygon meshes have their curved surfaces divided into a series of points. If you look at it closely, or print it very large, you will see not a curved but a faceted surface. In both vector images and BREP data, the position of any point on a curve is not stored in the geometry but calculated on the fly, with exact precision. In FreeCAD, all BREP-based geometry is handled by another piece of open source software, OpenCasCade. The main interface between FreeCAD and the OpenCasCade kernel is the Part Workbench. Most other workbenches build their functionality on top of the Part Workbench. Although other workbenches often offer more advanced tools to build and manipulate geometry, since they all actually manipulate Part objects, it is very useful to know how these objects work internally, and be able to use the Part tools since, being more simple, they can very often help you to work around problems that the more intelligent tools fail to solve properly. To illustrate the working of the Part Workbench, we will model this table, using only CSG operations (except the screws, for which we will use one of the addons, and the dimensions, which will see in the next chapter): Let's create a new document (Ctrl+N or menu File → New Document) to hold our table design. The document is initially called "unnamed" in the Model tab in the Combo View panel, but if you save the document (Ctrl+Shift+S or menu File → Save As) as a new FreeCAD document called "table.FCStd" the document will be renamed "table", which more clearly identifies the project. Now we can switch to the Part Workbench and start to create our first table leg. Press the Cube button Select the Cube, then set the following properties (in the Data tab): Length: 80mm (or 8cm, or 0.8m, FreeCAD works in any unit) Width: 80mm Height: 75cm Duplicate the Cube by pressing Ctrl+C then Ctrl+V (or menu Edit → Copy and Paste) (No change will be evident, as the second object is overlaying the first.) Select the new object named Cube001 that has been created (Click on Cube001 in the left side Model tab) Change its position by editing its Placement property: Position x: 8mm Position y: 8mm You should obtain two high cubes, one 8mm apart from the other: Now we can subtract one from the other: Select the first one, that is, the one that will stay, then, with the CTRL key pressed, select the other one, that will be subtracted (the order is important) and press the Cut button: Observe that the newly created object, called "Cut", still contains the two cubes we used as operands. In fact, the two cubes are still there in the document, they have merely been hidden and grouped under the Cut object in the tree view. You can still select them by expanding the arrow next to the Cut object, and, if you wish, turn them visible again by right-clicking them or change any of their properties. You can use Cut -tool and other Boolean tools also through "Combo view" with Boolean. It gives more explicit but longer way to do it. Now let's create the three other feet by duplicating our base cube 6 other times. Since it is still copied, you can simply paste (Ctrl+V) 6 times. Change their position as follows: Cube002: x: 0, y: 80cm Cube003: x: 8mm, y: 79.2cm Cube004: x: 120cm, y: 0 Cube005: x: 119.2cm, y: 8mm Cube006: x: 120cm, y: 80cm Cube007: x: 119.2cm, y: 79.2cm Now let's do the three other cuts, selecting first the "host" cube then the cube to be cut off. We now have four Cut objects: You might have been thinking that, instead of duplicating the base cube six times, we could have duplicated the complete foot three times. This is totally true, as always in FreeCAD, there are many ways to achieve a same result. This is a precious thing to remember, because, as we will advance into more complex objects, some operations might not give the correct result and we often need to try other ways. We will now make holes for the screws, using the same Cut method. Since we need 8 holes, two in each foot, we could make 8 objects to be subtracted. Instead, let's explore other ways and make 4 tubes, that will be reused by two of the feet. So let's create four tubes by using the Cylinder tool. You can again, make only one and duplicate it afterwards. Give all cylinders a radius of 6mm. This time, we will need to rotate them, which is also done via the Placement property under the Data tab (Note: change the Axis property before setting the Angle, or the rotation will not be applied): Cylinder: height: 130cm, angle: 90°, axis: x:0,y:1,z:0, position: x:-10mm, y:40mm, z:72cm Cylinder001: height: 130cm, angle: 90°, axis: x:0,y:1,z:0, position: x:-10mm, y:84cm, z:72cm Cylinder002: height: 90cm, angle: 90°, axis: x:-1,y:0,z:0, position: x:40mm, y:-10mm, z:70cm Cylinder003: height: 90cm, angle: 90°, axis: x:-1,y:0,z:0, position: x:124cm, y:-10mm, z:70cm You will notice that the cylinders are a bit longer than needed. This is because, as in all solid-based 3D applications, boolean operations in FreeCAD are sometimes oversensitive to face-on-face situations and might fail. By doing this, we put ourselves on the safe side. Now let's do the subtractions. Select the first foot, then, with CTRL pressed, select one of the tubes that crosses it, press the Cut button. The hole will be done, and the tube hidden. Find it in the tree view by expanding the pierced foot. Select another foot pierced by this hidden tube, then repeat the operation, this time Ctrl+ selecting the tube in the tree view, as it is hidden in the 3D view (you can also make it visible again and select it in the 3D view). Repeat this for the other feet until each of them has its two holes: As you can see, each foot has become a quite long series of operations. All this stays parametric, and you can go change any parameter of any of the older operations anytime. In FreeCAD, we often refer to this pile as "modeling history", since it in fact carries all the history of the operations you did. Another particularity of FreeCAD is that the concept of 3D object and the concept of 3D operation tend to blend into one same thing. The Cut is at the same time an operation, and the 3D object resulting from this operation. In FreeCAD this is called a "feature", rather than object or operation. Now let's do the tabletop, it will be a simple block of wood, let's do it with another Box with length: 126cm, width: 86cm, height: 8cm, position: x: 10mm, y: 10mm, z, 67cm. In the View tab, you can give it a nice brownish, wood-like color by changing its Shape Color property: Notice that, although the legs are 8mm thick, we placed it 10mm away, leaving 2mm between them. This is not necessary, of course, it won't happen with the real table, but it is a common thing to do in that kind of "assembled" models, it helps people who look at the model to understand that these are independent parts, that will need to be attached together manually later. Now that our five pieces are complete, it is a good time to give them more proper names than "Cut015". By right-clicking the objects in the tree view (or pressing F2), you can rename them to something more meaningful to yourself or to another person who would open your file later. It is often said that simply giving proper names to your objects is much more important than the way you model them. We will now place some screws. There is nowadays an extremely useful addon developed by a member of the FreeCAD community, that you can find on the FreeCAD addons repository, called Fasteners, that makes the insertion of screws very easy. Installing additional workbenches is easy and described on the addons pages. Once you have installed the Fasteners Workbench and restarted FreeCAD, it will appear in the workbenches list, and we can switch to it. Adding a screw to one of our holes is done by first selecting the circular edge of our hole: Then we can press one of the screw buttons of the Fasteners Workbench, for example the EN 1665 Hexagon bolt with flanges, heavy series. The screw will be placed and aligned with our hole, and the diameter will automatically be selected to match the size of our hole. Sometimes the screw will be placed inverted, which we can correct by flipping its invert property. We can also set its offset to 2mm, to follow the same rule we used between the tabletop and the feet: Repeat this for all the holes, and our table is complete! The internal structure of Part objects As we saw above, it is possible in FreeCAD to select not only whole objects, but parts of them, such as the circular border of our screw hole. This is a good time to have a quick look at how Part objects are constructed internally. Every workbench that produces Part geometry will be based on these: Vertices: These are points (usually endpoints) on which all the rest is built. For example, a line has two vertices. Edges: the edges are linear geometry like lines, arcs, ellipses or NURBS curves. They usually have two vertices, but some special cases have only one (a closed circle for example). Wires: A wire is a sequence of edges connected by their endpoints. It can contain edges of any type, and it can be closed or not. Faces: Faces can be planar or curved, and can be formed by one closed wire, which forms the border of the face, or more than one, in case the face has holes. Shells: Shells are simply a group of faces connected by their edges. It can be open or closed. Solids: When a shell is tightly closed, that is, it has no "leak", it becomes a solid. Solids carry the notion of inside and outside. Many workbenches rely on this to make sure the objects they produce can be built in the real world. Compounds: Compounds are simply aggregates of other shapes, no matter their type, into a single shape. In the 3D view, you can select individual vertices, edges or faces. Selecting one of these also selects the whole object. A note about shared design You might look at the table above, and think its design is not good. The tightening of the feet with the tabletop is probably too weak. You might want to add reinforcing pieces, or simply you have other ideas to make it better. This is where sharing becomes interesting. You can download the file made during this exercise from the link below, and modify it to make it better. Then, if you share that improved file, others might be able to make it even better, or use your well-designed table in their projects. Your design might then give other ideas to other people, and maybe you will have helped a tiny bit to make a better world... Downloads The file produced in this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/table.FCStd Read more The Part Workbench The FreeCAD addons repository The Fasteners Workbench


Manual:Traditional 2D drafting

Among the tools offered by the Draft Workbench, you will find traditional drawing tools like Line, Circle, or Wire (polyline), modification tools like Move, Rotate or Offset, a working plane/grid system that allows you to define precisely in which plane you are working, and a complete snapping system that makes it very easy to draw and position elements precisely in relation to each other. To showcase the workflow and possibilities of the Draft Workbench, we will walk through a simple exercise, the result of which will be this little drawing, showing the floor plan of a small house that contains only a kitchen top (A pretty absurd floor plan, but we can do what we want here, can't we?): Switch to the Draft Workbench As in all technical drawing applications, it is wise to set up your environment correctly, it will save you a lot of time. Configure the grid and working plane, Text and Dimension settings to your liking in menu Edit → Preferences → Draft. In this exercise, however, we will act as if these settings were left at their default values. One option might need your attention, though: the "Fill objects with faces whenever possible" option. If this is marked, closed objects like rectangles or circles will be filled with a face by default, which can make snapping to underlying objects difficult. You can either turn this option off now, or, later on, turn the "Make Face" property of each individual object off, to prevent them from creating a face. The Draft Workbench also has two special toolbars: One with visual settings, where you can change the current working plane, turn construction mode on/off, set the line color, face color, line weight and text size to be used for new objects, and another one with snap locations. There, you can turn the grid on/off and set/unset individual Snap locations: Turning on all the snap buttons is convenient, but also makes drawing slower, as more calculation needs to be done when you move the mouse cursor. It is often better to keep only the ones you will actually use. Let's start by turning construction mode on, which will allow us to draw some guidelines on which we will draw our final geometry. If you wish, set the working plane to XY. If you do this, the working plane won't change, no matter the current view. If not, the working plane will adapt automatically to the current view, and you should take care of staying in top view whenever you want to draw on the XY (ground) plane. Then, select the Rectangle tool and draw a rectangle, starting at point (0,0,0), of 2 meters by 2 meters (leave the Z at zero). Note that most of the Draft commands can be fully performed from the keyboard, without touching the mouse, using their two-letter shortcut. Our first 2x2m rectangle can be done like this: re 0 Enter 0 Enter 0 Enter 2m Enter 2m Enter 0 Enter. Duplicate that rectangle by 15cm inside, using the Offset tool, turning its Copy mode on, and giving it a distance of 15cm: We can then draw a couple of vertical lines to define where our doors and windows will be placed, using the Line tool (note that the "relative" mode box should be unchecked for this step). The crossing of these lines with our two rectangles will give us useful intersections to snap our walls to. Draw the first line from point (15cm, 1m, 0) to point (15cm, 3m, 0). Duplicate that line 5 times, using the Move tool with Copy mode turned on. Turn also the Relative mode on, which will allow us to define movements in relative distances, which is easier than calculating the exact position of each line. Perform each move operation in sequence on the line that was created immediately prior. Give each new copy any start point, you can leave it at (0,0,0) for example, and the following relative endpoints: line001: x: 10cm line002: x: 120cm line003: x: -55cm, y: -2m line004: x: 80cm line005: x: 15cm That is all we need now, so we can switch construction mode off. Check that all the construction geometry has been placed into a "Construction" group, which makes it easy to hide it all at once or even delete it completely later on. Now let's draw our two wall pieces using the Wire tool. Make sure the intersection snap is turned on, as we will need to snap to the intersections of our lines and rectangles. Draw two wires as follows, by clicking all the points of their contours. To close them, either click on the first point again, or press the Close button: We can change their default grey color to a nice hatch pattern, by selecting both walls, then setting their Pattern property to Simple, and their Pattern size to your liking, for example 0.005. We can now hide the construction geometry by right-clicking the Construction group and choose Hide Selection. Let's now draw the windows and doors. Make sure the midpoint snap is turned on, and draw six lines as follow: We will now change the door line to create an opened door symbol. Start by rotating the line using the Rotate tool. Click the endpoint of the line as rotation center, give it a start angle of 0, and an end angle of -90. Then create the opening arc with the Arc tool. Pick the same point as the rotation center we used in the previous step as center, click the other point of the line to give the radius, then the start and end points as follow: We can now start placing some furniture. To begin with, let's place a counter by drawing a rectangle from the upper left inner corner, and giving it a width of 170cm and a height of -60cm. In the image below, the Transparency property of the rectangle is set to 80%, to give it a nice furniture look. Then let's add a sink and a cookertop. Drawing these kinds of symbols by hand can be very tedious, and they are usually easy to find on the internet, for example on http://www.cad-blocks.net . In the Downloads section below, for convenience, we separated a sink and a cookertop from this project, and saved them as DXF files.You can download these two files by visiting the links below, and right-clicking the Raw button, then choosing save as. Inserting a DXF file into an opened FreeCAD document can be done either by choosing the File → Import menu option, or by dragging and dropping the DXF file from your file explorer into the FreeCAD window. The contents of the DXF files might not appear right on the center of your current view, depending on where they were in the DXF file. You can use menu View → Standard views → Fit all to zoom out and find the imported objects. Insert the two DXF files, and move them to a suitable location on the tabletop: We can now place a couple of dimensions using the Dimension tool. Dimensions are drawn by clicking 3 points: the start point, an end point, and a third point to place the dimension line. To make horizontal or vertical dimensions, even if the two first points are not aligned, press Shift while clicking the second point. You can change the position of a dimension text by double-clicking the dimension in the tree view. A control point will allow you to move the text graphically. In our exercise, the "0.15" texts have been moved away for better clarity. You can change the contents of the dimension text by editing their Override property. In our example, the texts of the door and window dimensions have been edited to indicate their heights: Let's add some description texts using the Text tool. Click a point to position the text, then enter the lines of text, pressing Enter after each line. To finish, press Enter twice. The indication lines (also called "leaders") that link the texts to the item they are describing are simply done with the Wire tool. Draw wires, starting from the text position, to the place being described. Once that is done, you can add a bullet or arrow at the end of the wires by setting their End Arrow property to true Our drawing is now complete! Since there are quite a number of objects there, it would be wise do some cleaning and restructure everything into nice groups, to make the file easier to understand for other people: We can now print our work by placing it on a Drawing sheet, which we will show later in this manual, or directly export our drawing to other CAD applications, by exporting it to a DXF file. Simply select our "Floor plan" group, select menu File → Export, and select the Autodesk DXF format. The file can then be opened in any other 2D CAD application such as LibreCAD. You might notice some differences, depending on the configurations of each application. The most important thing about the Draft Workbench, however, is that the geometry you create with it can be used as a base or easily extruded into 3D objects, simply by using the Part_Extrude tool from the Part Workbench, or, to stay in Draft, the Trimex (Trim/Extend/Extrude) tool, which under the hood performs a Part Extrusion, but does it "the Draft way", that is, allows you to indicate and snap the extrusion length graphically. Experiment extruding our walls as shown below. By pressing the working plane button after selecting a face of an object, you are also able to place the working plane anywhere, and therefore draw Draft objects in different planes, for example on top of the walls. These can then be extruded to form other 3D solids. Experiment setting the working plane on one of the top faces of the walls, then draw some rectangles up there. All kinds of openings can also be done as easily by drawing Draft objects on the faces of walls, then extruding them, then using the boolean tools from the Part Workbench to subtract them from another solid, as we saw in the previous chapter. Fundamentally, what the Draft Workbench does is to provide graphical ways to create basic Part operations. While in Part you will usually position objects by setting their placement parameter, in Draft you can do it on-screen. There are times when one is better, other times when the other is preferable. Don't forget, you can create custom toolbars in one of these workbenches, add the tools from the other, and get the best of both worlds.

Downloads

The file created during this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/cabin.FCStd The sink DXF file: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/sink.dxf The cookertop DXF file: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/cooktop.dxf The final DXF file produced during this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/cabin.dxf

Related

The Draft Workbench Snapping The Draft working plane


Manual:Preparing models for 3D printing

Making sure that your 3D objects are solid. Real-world objects are solid, the 3D model must be solid too. We saw in earlier chapters that FreeCAD helps you a lot in that regard, and that the PartDesign Workbench will notify you if you do an operation that prevents your model to stay solid. The Part Workbench also contains a Check Geometry tool that is handy to check further for possible defects. Making sure about the dimensions of your objects. One millimeter will be one millimeter in real-life. Every dimension matters. Controlling the degradation. No 3D printing or CNC milling system can take FreeCAD files directly. Most of them will only understand a machine language called G-Code. G-code has dozens of different dialects, each machine or vendor usually has its own. The conversion of your models into G-Code can be easy and automatic, but you can also do it manually, with total control over the output. In any case, some loss of quality of your model will unavoidably occur during the process. When printing in 3D, you must always make sure this loss of quality stays below your minimum requirements. Below, we will assume that the first two criteria are met, and that by now you are able to produce solid objects with correct dimensions. We will now see how to address the third point. 1 Exporting to slicers 2 Converting objects to meshes 3 Using Slic3r 4 Using the Cura addon 5 Generating G-code 6 Videos

Exporting to slicers

This is the technique most commonly used for 3D printing. The 3D object is exported to another program (the slicer) which will generate the G-code from the object, by slicing it into thin layers (hence the name), which will reproduce the movements that the 3D printer will do. Since many of those printers are home-built, there are often small differences from one to the other. These programs usually offer advanced configuration possibilities that allow you to tailor the output exactly for the features of your 3D printer. Actual 3D printing, however, is too vast a subject for this manual. But we will see how to export and use these slicers to check that the output is correct.

Converting objects to meshes

None of the slicers will, at this time, directly take the solid geometry as we produce in FreeCAD. So we will need to convert any object we want to 3D print into a mesh first, that the slicer can open. Fortunately, as much as converting a mesh to a solid is a complicated operation, the contrary, converting a solid to a mesh, is very straightforward. All we need to be careful about, is that it is here that the degradation we mentioned above will occur. We need to check that the degradation stays within acceptable limits. All the mesh handling, in FreeCAD, is done by another specific workbench, the Mesh Workbench. This workbench contains, in addition to the most important tools that convert between Part and Mesh objects, several utilities meant to analyze and repair meshes. Although working with meshes is not the focus of FreeCAD, when working with 3D modeling, you often need to deal with mesh objects, since their use is very widespread among other applications. This workbench allows you to handle them fully in FreeCAD. Let's convert one of the objects we modelled in the previous chapters, such as the lego piece (which can be downloaded from the end of the previous chapter). Open the FreeCAD file containing the lego piece. Switch to the Mesh Workbench Select the lego brick Select menu Meshes → Create Mesh from Shape A task panel will open with several options. Some additional meshing algorithms (Mefisto or Netgen) might not be available, depending on how your version of FreeCAD was compiled. The Standard meshing algorithm will always be present. It offers less possibilities than the two others, but is totally sufficient for small objects that fit into the maximum print size of a 3D printer. Select the Standard mesher, and leave the deviation value to the default value of 0.10. Press Ok. A mesh object will be created, exactly on top of our solid object. Either hide the solid, or move one of the objects aside, so you can compare both. Change the View → Display Mode property of the new mesh object to Flat Lines, in order to see how the triangulation occurred. If you are not happy, and think that the result is too coarse, you can repeat the operation, lowering the deviation value. In the example below, the left mesh used the default value of 0.10, while the right one uses 0.01: In most cases, though, the default values will give a satisfying result. We can now export our mesh to a mesh format, such as STL, which is currently the most widely used format in 3D printing, by using menu File → Export and choosing the STL file format. If you don't own a 3D printer, it is usually very easy to find commercial services that will print and send you the printed objects by mail. Among the famous ones are Shapeways and Sculpteo, but you will usually find many others in your own city. In all major cities, you will nowadays find Fab labs, which are workshops equipped with a range of 3D manufacturing machines, almost always including at least one 3D printer. Fab labs are usually community spaces, that will let you use their machines, for a fee or for free depending on the Fab lab, but also teach you how to use them, and promote other activities around 3D manufacturing.

Using Slic3r

Slic3r is an application that converts STL objects into G-code that can be sent directly to 3D printers. Like FreeCAD, it is free, open source and runs on Windows, Mac OS and Linux. Correctly configuring things for 3D printing is a complicated process, where you must have a good knowledge of your 3D printer, so it is not very useful to generate G-code before actually going to print (your G-code file might not work well on another printer), but it is useful for us anyway, to check that our STL file will be printable without problems. This is our exported STL file opened in Slic3r. By using the preview tab, and moving the right slider, we can visualize the path that the 3D printer head will follow to construct our object.

Using the Cura addon

Cura is another free and open source slicer application for Windows, Mac and Linux, maintained by the 3D printer maker Ultimaker. Some FreeCAD users have created a Cura Workbench that uses cura internally. The Cura Workbench is available from the FreeCAD addons repository. To use the Cura Workbench, you also need to install Cura itself, which is not included in the workbench. Once you have installed both Cura and the Cura Workbench, you will be able to use it to produce the G-code file directly from Part objects, without the need to convert them to meshes, and without the need to open an external application. Producing another G-code file from our Lego brick, using the Cura Workbench this time, is done as follows: Load the file containing our Lego brick (it can be downloaded at the end of the previous chapter) Switch to the Cura Workbench Setup the printer space by choosing menu 3D printing → Create a 3D printer definition. Since we aren't going to print for real, we can leave the settings as they are. The geometry of the printing bed and available space will be shown in the 3D view. Move the Lego brick to a suitable location, such as the center of the printing bed. Remember that PartDesign objects cannot be moved directly, so you need either to move its very first sketch (the first rectangle), or to move (and print) a copy, which can be made with the Part -> Create Simple Copy tool. The copy can be moved, for example with Draft → Move. Select the object to be printed, and select menu 3D printing → Slice with Cura Engine. In the task panel that will open, make sure the path to the Cura executable is correctly set. Since we are not going to really print, we can leave all other options as they are. Press Ok. Two files will be generated in the same directory as your FreeCAD file, an STL file and a G-code file. The generated G-code can also be re-imported into FreeCAD (using the slic3r preprocessor) for checking.

Generating G-code

FreeCAD also offers more advanced ways to generate G-code directly. This is often much more complicated than using automatic tools as we saw above, but has the advantage to let you fully control the output. This is usually not needed when using 3D printers, but becomes very important when dealing with CNC milling, as the machines are much more complex. G-code path generation in FreeCAD is done with the Path Workbench. It features tools that generate full machine paths and others that generate only parts of a G-code project, that can then be assembled to form a whole milling operation. Generating CNC milling paths is another subject that is much too vast to fit in this manual, so we are going to show how to build a simple Path project, without caring much about most of the details of real CNC machining. Load the file containing our lego piece, and switch to the Path Workbench. Since the final piece doesn't contain anymore a rectangular top face, hide the final lego piece, and show the first cubic pad that we did, which has a rectangular top face. Select the top face and press the Profile button. Set its Offset property to 1mm. Then, let's duplicate this first loop a couple of times, so the tool will carve out the whole block. Select the Profile path, and press the Array button. Set the Copies property of the array to 8, and its Offset to -2mm in the Z direction, and move the placement of the array by 2mm in the Z direction, so the cutting will start a bit above the pad, and include the height of the dots too. Now we have defined a path that, when followed by the milling machine, will carve a rectangular volume out of a block of material. We now need to carve out the space between the dots, in order to reveal them. Hide the Pad, and show the final piece again, so we can select the face that lies between the dots. Select the top face, and press the Pocket Shape button. Set the Offset property to 1mm, and the retraction height to 20mm. That is the height to where the cutter will travel when switching from one loop to another. Otherwise, the cutter might cut right through one of our dots: Once again, make an array. Select the Pocket object, and press the Array button. Set the Copies number to 1 and the offset to -2mm in the Z direction. Move the placement of the array by 2mm in the Z direction. Our two operations are now done: Now all that is left to do is to join these two operations into one. This can be done with a Path Job. Press the Job button. Set the Use Placements property of the project is to True, because we changed the placement of the arrays, and we want that to be taken into account in the project. In the tree view, drag and drop the two arrays into the project. You can reorder the arrays inside the project if needed, by double-clicking it. The project can now be exported to G-code, by selecting it, choosing menu File -> Export, selecting the G-code format, and in the pop-up dialog that will open, selecting a post-processing script according to your machine. There are many applications available to simulate the real cutting, one of them that is also multi-platform and open source, like FreeCAD, is Camotics. Downloads The STL file generated in this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/lego.stl The file generated during this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/path.FCStd The G-code file generated in this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/lego.gcode Read more The Mesh Workbench The STL file format Slic3r Cura The Cura Workbench The Path Workbench Camotics

Videos

How To Use FreeCAD For 3D Printing | Using The Realthunder Branch A video playlist by Maker Tales about how to use FreeCAD for 3D printing.


SAMPLE TUTORIAL


Manual:Generating 2D drawings

In FreeCAD, the workbench responsible for making such drawings is the TechDraw Workbench. The TechDraw Workbench allows you to create sheets, which can be blank or use a pre-made template to already have a series of items on the sheet, such as borders and a title. On these sheets, you can then place views of the 3D objects you modeled previously, and configure how these views will appear on the sheet. You can also place all kinds of annotations on the sheet, such as dimensions, texts, and other symbols commonly used in technical drawings. Drawing sheets, once complete, can be printed or exported as SVG, PDF or DXF files. In the following exercise, we will see how to create a simple drawing of a chair model found in the FreeCAD library (Furniture → Chairs → IkeaLikeChair). The FreeCAD library can easily be added to your FreeCAD installation (refer to the installing chapter of this manual), or you can simply download the model from the library webpage, or via the direct link provided at the bottom of this chapter. Load the IkeaLikeChair file from the library. You can choose between the .FCStd version, which will load the full modeling history, or the .step version, which will create only one object, without the history. Since we won't need to model any further now, it is best to choose the .step version, as it will be easier to manipulate. Switch to the TechDraw Workbench Press the TechDraw PageTemplate button. Select the A4_Portrait_ISO7200TD template. A new tab will open in your FreeCAD window, showing the new page. In the tree view (or in the model tab), select the chair model. It will most likely be named something like "Open CASCADE STEP translator." Press the TechDraw View button. A View object will be created on our page. Select the view object in the tree view, and then give the view the following properties in the data tab of the combo view: Under the Base category: X: 70 mm Y: 120 mm Rotation: 0 Scale: 0.1 Under the Projection category (hit the drop down arrow to modify the x, y, and z components of these properties individually): Direction: [0 0 1] XDirection: [0 -1 0] (Change the y field first, then the x field) We now have a nice top view of our chair. Hit the TechDraw ToggleFrame button to turn the View frames, labels, and vertices off. Let's repeat the operation twice, to create two more views. We will set their X and Y values, which indicate the position of the view on the page, in order to show them apart from the top view, and their direction, to create different view orientations. Give each new view the following properties: View001 (front view): X: 70, Y: 220, Scale: 0.1, Rotation: 0, Direction: (-1,0,0), XDirection: (0,-1,0) View002 (side view): X: 150, Y: 220, Scale: 0.1, Rotation: 0, Direction: (0,-1,0), XDirection: (1,0,0) After that, we obtain the following page: Note that there may be easier ways to get the views that you want. You can simply rotate the 3D view of your model, and once you have the view you want, select the model in the tree view and hit New View. This will automatically insert a view with the desired rotation and direction properties. You can also use the TechDraw ProjectionGroup tool. We can tweak the aspect of our views if we want, for example we can change their Line Width property (under the View tab in the Combo View) to 0.5. We will now place dimensions and indications on our drawing. There are two ways to add dimensions to a model: one is placing the dimensions inside the 3D model, using the Dimension tool of the Draft Workbench, and then placing a view of these dimensions on our sheet with the TechDraw DraftView tool. The other is to do things directly on the TechDraw sheet. We'll use the latter method. Hit the Toggle button to turn the vertices on. Use Ctrl + Left Mouse Click to select the two vertices you want to measure the distance between. Hit the TechDraw LengthDimension button. Repeat the operation, until all the dimensions you wish to indicate are placed. Use the TechDraw VerticalDimension and TechDraw HorizontalDimension tools as necessary. Take a minute to look at the properties of the Dimension object in the Combo View. Please note that if you are dimensioning an axonometric view (e.g., isometric view) instead of a multiview view (e.g., front view) like we have done here, you will need to use the TechDraw LinkDimension tool to get an accurate dimension. We will now place the two callouts shown in the image above, using the TechDraw Balloon tool. Looking at the Page in the 3D view window, select the View to which the Balloon will be attached, as shown in the image above. Press the Balloon button. The cursor is now displayed as a balloon icon. Click on the page to place the balloon origin at the desired position. The balloon bubble may be dragged to the desired position. Change the balloon properties by double clicking the balloon label or the balloon object in the tree view. This will open the Balloon Task dialog. Set the Value field to the desired text and change the Symbol drop-down menu selection to None Press OK Repeat the operation for the second callout. We will now fill in the sheet title block. Make sure that the View frames, labels, and vertices are visible. If not, hit the Toggle button. Edit the text in each section of the sheet title block by clicking on the small green square on the left side of the text. Our page can now be exported to SVG for further work in graphical applications like Inkscape or to DXF. Select the page in the tree view and then select menu File → Export. The DXF format is importable in almost all existing 2D CAD applications. TechDraw pages can also be directly printed or exported to PDF. Downloads The file created during this exercise: drawing.FCStd The SVG sheet produced from that file: drawing.svg Read more The TechDraw workbench Create custom templates Another TechDraw tutorial The FreeCAD library Inkscape Watch tutorials Sliptonic's TechDraw playlist Symbols and Views


Manual:BIM modeling

This documentation is not finished. Please help and contribute documentation. GuiCommand model explains how commands should be documented. Browse Category:UnfinishedDocu to see more incomplete pages like this one. See Category:Command Reference for all commands. See WikiPages to learn about editing the wiki pages, and go to Help FreeCAD to learn about other ways in which you can contribute. As in the PartDesign Workbench, the objects produced by the Arch Workbench are meant to be built in the real world. Therefore, they need to be solid. The Arch tools usually take care of that automatically, and also provide utility tools to help you check the validity of objects. The Arch Workbench also includes all the tools from the Draft Workbench, and uses its grid and snapping system. Before beginning, it is always a good idea to browse through the preferences pages of both Draft and Arch and set the default settings to your liking. In this chapter, we will see how to model this small building: and produce a plan and a section view from it: Create a new document, and switch to the Arch Workbench. Open menu Edit → Preferences → Draft → Grid and Snapping and set: Main lines every 10. Grid spacing 1000mm to have a one meter-based grid, which is convenient for the size of our building. Grid size 100 lines. On the snapping toolbar make sure the grid snap button is enabled, so we can use the grid as much as possible. If you do not see the axes then click the toggle draft grid button. Set the Working Plane to XY plane Zoom out and pan so you can see the area from (0,0) to (4,3). See the Mouse navigation for instructions. Draw four lines with the Draft Line tool. You can enter coordinates manually, or simply pick the points on the grid with the mouse: From point (0,0) to point (0,3) From point (0,3) to point (4,3) From point (4,3) to point (4,0) From point (4,0) to point (0,0) NOTE: Due to a bug in version 0.18, make sure you do the lines in this order and this direction. Notice that we drew always in the same direction (clockwise). This is not necessary, but will ensure that the walls that we will build next all have the same left and right directions. You might also think we could simply have drawn a rectangle here, which is true. But the four lines will allow us to illustrate better how to add one object into another. Once your have created the lines check their start and end points and adjust if necessary to get them exactly correct. Select the first line, then press the Wall button. Repeat this for the 3 other lines, until you have 4 walls. Select the four walls, and set their Height property to 3.00m and their Alignment property to left. If you didn't draw the lines in the same order as we did above, some of the walls might have their left and right directions flipped, and might need to be set to right instead. You will obtain four intersecting walls, on the inside of the baselines: Now we need to join these walls together, so they intersect properly. This is not necessary when your walls are drawn in a way that they already connect cleanly, but here we need to, since they are intersecting. In Arch, this is done by electing one of the walls to be the "host", and adding the others to it, as "additions". All arch objects can have any number of additions (objects whose geometry will be added to the host's geometry), and subtractions (objects whose geometry will be subtracted). The additions and subtractions of an object can be managed anytime by double-clicking the object in the tree. Select the four walls with Ctrl pressed, the last one being the wall that you chose to become the host Press the Add button. The four walls have now been turned into one: The individual walls are however still accessible, by expanding the wall in the tree view. Let's now place a door. In FreeCAD, doors are considered a special case of windows, so this is done using the Window tool. Start by selecting the wall. This is not necessary, but a good habit to take. If an object is selected when starting the window tool, you will force the window to be inserted in that object, even if you snap to another object. Set the Working Plane to auto so we are not restricted to the ground plane Press the Window button. In the window creation panel, select the Simple door preset, and set its Width to 0.9m and its Height to 2.1m Make sure the Near snap location is turned on, so we can snap on faces Place your window roughly on the middle of the front face of the wall: After clicking, our window is placed on the correct face, but not exactly where we want: We can now set the precise location by expanding the wall and the window objects in the tree view, and changing the Placement property of the base sketch of our door. Set its position to x = 2m, y = 0, z = 0. Our window is now exactly where we want it: Repeat the operation to place a window: Select the wall, press the window tool, select the Open 2-pane preset, and place a 1m x 1m window in the same face as the door. Set the placement of the underlying sketch to position x = 0.6m, y = 0, z = 1.1m, so the upper line of the window is aligned to the top of the door. Windows are always built on sketches. It is easy to create custom windows by first creating a sketch on a face, then turning it into a window by selecting it, then pressing the window button. Then, the window creation parameters, that is, which wires of the sketch must be extruded and how much, can be defined by double-clicking the window in the tree view. Now, let's create a slab: Set the Working Plane to XY plane Create a rectangle with a length of 5m, a height of 4m, and place it at position x:-0.5m, y:-0.5m, z:0. Select the rectangle Click the structure tool to create a slab from the rectangle Set the height property of the slab to 0.2m and its normal direction to (0,0,-1) because we want it to extrude downwards. We could also simply have moved it 0.2m down, but it is always good practice to keep extruded objects at the same place as their base profile. Set the Role property of the slab to slab. This is not necessary in FreeCAD, but is important for IFC export, as it will ensure that the object is exported with the correct IFC type. Let's now use one of the structural presets to make a metallic beam. Click the structure button, select a HEB 180 preset, and set its height to 4m. Place it anywhere: Adjust its placement by setting its Angle to 90° in the (1,0,0) axis, and its position to x:90mm, y:3.5m, z:3.09m. This will position the beam exactly on one of the side walls: We need now to duplicate this beam a couple of times. We could do that one by one using the clone tool, but there is a better way, to do all the copies at once using an array: Select the beam Press the Draft OrthoArray button Set the Number of elements for the X direction of the array to 6, set the number for the Y and Z direction to 1, and press OK. Expand the interval X property of the array, and press the small expression icon at the right side of the X field. This will open an expressions editor: Write (4m-180mm)/5 in the expression field, and press OK. This will set the x value to 0.764 (4m is the total length of our front wall, 180mm is the width of the beam, which is why it is called HEB180, and we want a fifth of that space as interval between each beam): We can now easily build a simple slab on top of them, by drawing a rectangle directly on the top plane of the beams. Select a top face of one of the beams Press the working plane button. The working plane is now set to that face. Create a rectangle, snapping to two opposite points of the border beams: Select the rectangle Click the structure button and create a slab with a height of 0.2m. That's it, our model is now complete. We should now organize it so it exports correctly to IFC. The IFC format requires that all objects of a building are inside a building object, and optionally, inside a story. It also requires that all buildings are placed on a site, but the IFC exporter of FreeCAD will add a default site automatically if needed, so we don't need to add one here. Select the two slabs, the wall, and the array of beams Press the Floor button Select the floor we just created Press the Building button Our model is now ready to export: The IFC format is one of the most precious assets in a free BIM world, because it allows the exchange of data between any application and actor of the construction world, in an open manner (the format is open, free and maintained by an independent consortium). Exporting your BIM models as IFC ensures that anyone can see and analyze them, no matter the application used. In FreeCAD, IFC import and export is done by interfacing with another piece of software, called IfcOpenShell. To be able to export to IFC from FreeCAD, the IfcOpenShell-python package must be installed on your system. Be sure to select one which uses the same python version as FreeCAD. The python version that FreeCAD uses is informed when opening the View -> Panels -> Python console panel in FreeCAD. When that is done, we can now export our model: Select the top object you want to export, that is, the Building object. Select menu File -> Export -> Industry Foundation Classes and save your file. The resulting IFC file can now be opened in a wide range of applications and viewers (the image below shows the file opened in the free IfcPlusPlus viewer). Checking the exported file in such a viewer application before distributing it to other people is important to check that all the data contained in the file is correct. FreeCAD itself can also be used to re-open the resulting IFC file. We will now place some dimensions. Unlike the previous chapter, where we drew all the dimensions directly on the Drawing sheet, we will use another method here, and place Draft dimensions directly in the 3D model. These dimensions will then be placed on the Drawing sheet automatically. We will first make two groups for our dimensions, one for the dimensions that will appear in the plan view, and another for those that appear on the elevation. Right-click the "house" document in the tree view, and create two new groups: Plan dimensions and Elevation dimensions. Set the Working Plane to XY plane Make sure the restrict snap location is turned on, so everything you draw stays on the working plane. Draw a couple of Dimensions, for example as on the image below. Pressing Shift and Ctrl while snapping the dimension points will give you additional options. Select all your dimensions, and drag them to the Plan dimensions group in the tree view Set the Working Plane to XZ plane, that is, the frontal vertical plane. Repeat the operation, draw a couple of dimensions, and place them in the Elevation dimensions group. We will now prepare a set of views from our model, to be placed on a Drawing page. We can do that with the tools from the Drawing Workbench, as we have seen in the previous chapter, but the Arch Workbench also offers an all-in-one advanced tool to produce plan, section and elevation views, called Section Plane. We will now add two of these section planes, to create a plan view and an elevation view. Select the building object in the tree view Press the Section Plane button. Set its Display Height property to 5m, its Display Length to 6m, so we encompass our house (this is not needed, but will look better, as it will show naturally what it is used for), and its Placement position at x:2m, y:1.5m, z:1.5m. Check the list of objects considered by the Section Plane by double-clicking it in the tree view. Section Planes only render specified objects from the model, not all of them. The objects considered by the Section Plane can be changed here. Repeat the operation to create another section plane, give it the same display length and height, and give it the following Placement: position: x:2m, y:-2m, z:1.5m, angle: 90°, axis: x:1, y:0, z:0. Make sure this new section plane also considers the building object. Now we have everything we need, and we can create our Drawing page. Start by switching to the Drawing Workbench, and create a new default A3 page (or select another template if you wish). Select the first section plane, used for the plan view Press the Draft View button. This tool offers a couple of additional features over the standard Drawing View tool, and supports the Section Planes from the Arch Workbench. Give the new view the following properties: X: 50 Y: 140 Scale: 0.03 Line width: 0.15 Show Cut True Show Fill: True Select the other section plane, and create a new Draft View, with the following properties: X: 250 Y: 150 Scale: 0.03 Rendering: Solid We will now create two more Draft Views, one for each group of dimensions. Select the Plan dimensions group Press the Draft View button. Give the new view the following properties: X: 50 Y: 140 Scale: 0.03 Line width: 0.15 Font size: 10mm Repeat the operation for the other group, with the following settings: X: 250 Y: 150 Scale: 0.03 Line width: 0.15 Font size: 10mm Direction: 0,-1,0 Rotation: 90° Our page is now ready, and we can export it to SVG or DXF formats, or print it. The SVG format allows you to open the file using illustration applications such as Inkscape, with which you can quickly enhance technical drawings and turn them into much nicer presentation drawings. It offers many more possibilities than the DXF format.

Downloads

The file produced during this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/house.FCStd The IFC file exported from the above file: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/house.ifc The SVG file exported from the above file: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/house.svg

Related

BIM Workbench The Arch Workbench The Draft working plane The Draft snapping settings The expressions system The IFC format IfcOpenShell IfcPlusPlus Inkscape


Manual:Using spreadsheets

In the following example, we will create a couple of objects, retrieve some of their properties in a spreadsheet, then use the spreadsheet to directly drive properties of other objects.

Reading properties

Start by switching to the Part Workbench, and create a couple of objects: a box, a cylinder and a sphere. Edit their Placement property (or use the Draft Move tool) to place them a little apart, so we can better see the effects of what we'll do: Now, let's extract some information about these objects. Switch to the Spreadsheet Workbench Press the New Spreadsheet button Double-click the new Spreadsheet object in the tree view. The spreadsheet editor opens: The spreadsheet editor of FreeCAD, although it is not as complete and powerful as the more complete spreadsheet applications we listed above, has nevertheless most of the basic tools and functions that are commonly used, such as the possibility to change the aspect of the cells (size, color, alignment), join and split cells, use formulas such as =2+2, or reference other cells with =B1. In FreeCAD, on top of these common features, there is a new interesting one: The possibility to reference not only other cells, but other objects from the document, and retrieve values from their properties. For example, let's retrieve a couple of properties from the 3 objects we created above. Properties are what we can see in the properties editor window, under the Data tab, when an object is selected. Let's start by entering a couple of texts in the cells A1, A2 and A3, so we remember what is what later on, for example Cube Length, Cylinder Radius and Sphere Radius. To enter text, just write in the "Contents" field above the spreadsheet, or double-click a cell. Now let's retrieve the actual length of our cube. In cell B1, type =Cube.Length. You will notice that the spreadsheet has an autocompletion mechanism, which is actually the same as the expression editor we used in the previous chapter. Do the same for cell B2 (=Cylinder.Radius) and B3 (=Sphere.Radius). Although these results are expressed with their units, the values can be manipulated as any number, try for example entering in cell C1: =B1*2. We can now change one of these values in the properties editor, and the change will be immediately reflected in the spreadsheet. For example, let's change the length of our cube to 20mm: The Spreadsheet Workbench page will describe in more detail all the possible operations and functions available in spreadsheets.

Writing properties

Another very interesting use of the Spreadsheet Workbench in FreeCAD is to do the contrary of what we have been doing until now: Instead of reading the values of properties of 3D objects, we can also assign values to these objects. Remember, however, one of the fundamental rules of FreeCAD: Circular dependencies are forbidden. We can therefore not use the same spreadsheet to read and write values to a 3D object. That would make the object depend on the spreadsheet, which would also depend on the object. Instead, we will create another spreadsheet. We can now close the spreadsheet tab (under the 3D view). This is not mandatory, there is no problem in keeping several spreadsheet windows open. Press the New Spreadsheet button again Change the name of the new spreadsheet to something more meaningful, such as Input (do this by right-clicking the new spreadsheet object, and choosing Rename). Double-click the Input spreadsheet to open the spreadsheet editor. In cell A1, let's put a descriptive text, for example: "Cube dimensions" In cell B1, write =5mm (using the = sign makes sure the value is interpreted as a unit value, not a text). Now to be able to use this value outside the spreadsheet, we need to give a name, or alias, to the B1 cell. Right-click the cell, click Properties and select the Alias tab. Give it a name, such as cubedims: Press OK, then close the spreadsheet tab Select the cube object In the properties editor, click the little expression icon at the right side of the Length field. This will open the expressions editor, where you can write Spreadsheet001.cubedims. Repeat this for Height and Width: You might wonder why we had to use "Spreadsheet001" instead of "Input" in the expression above. This is because each object, in a FreeCAD document, has an internal name, which is unique in the document, and a label, which is what appears in the tree view. If you uncheck the relevant option in the preferences window, FreeCAD will allow you to give the same label to more than one object. This is why all operations that must identify an object uniquely, will use the internal name instead of the label, which could designate more than one object. The easiest way to know the internal name of an object is by keeping the selection panel (menu bar View → Panels) open, it will always indicate the internal name of a selected object: By using cell aliases in spreadsheets, we are able to use a spreadsheet to store "master values" in a FreeCAD document. This can be used, for example, to have a model of a piece of certain dimensions, and to store these dimensions in a spreadsheet. It then becomes very easy to produce another model with different dimensions, it is just a matter of opening the file and changing a couple of dimensions in the spreadsheet. Finally, note that the constraints inside a sketch can also receive the value of a spreadsheet cell: You can also give aliases to dimensional constraints (horizontal, vertical or distance) in a sketch (you can then use that value from outside the sketch as well): Download The file produced in this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/spreadsheet.FCStd Read more The Spreadsheet Workbench The Expressions engine


Manual:Creating FEM analyses

Preparing FreeCAD

The simulation itself is done by another piece of software, that is used by FreeCAD to obtain the results. As there are several interesting open source FEM simulation applications available, the FEM Workbench allows you to choose between them. However, currently only CalculiX is fully implemented. Another piece of software, called NetGen, which is responsible for generating the subdivision mesh, is also required. Detailed instructions to install these two components are provided in the FreeCAD documentation.

Preparing the geometry

We will start with the house we modeled in the BIM modeling chapter. However, some changes have to be made to make the model suitable for FEM calculations. This involves, basically, discarding the objects that we don't want to include in the calculation, such as the door and window, and joining all the remaining objects into one. Load the house model we modeled earlier Delete or hide the page object, the section planes and the dimensions, leaving only our model Hide the window, the door and the ground slab Also hide the metal beams on the roof. They are very different objects from the rest of the house so we will simplify our calculation by not including them. Instead, we will assume that the roof slab is placed directly on top of the wall. Now move the roof slab down so it rests on top of the wall: Edit the Rectangle object that we used as a base of the roof slab, and change its Placement->Position->X value from 3.18m to 3.00m Our model is now clean: The FEM Workbench can currently only calculate deformations on a single object. Therefore, we need to join our two objects (the wall and the slab). Switch to the Part Workbench, select the two objects, and press the Union button. We have now obtained a fused object:

Creating the analysis

We are now ready to start a FEM analysis. Let's switch to the FEM Workbench Select the fused object Press the New Analysis button A new analysis will be created and a settings panels opened. Here you can define the meshing parameters to be used to produce the FEM mesh. The main setting to edit is the Max Size which defines the maximum size (in millimeters) of each piece of the mesh. For now, we can leave the default value of 1000: After pressing the OK button and a few seconds of calculation, our FEM mesh is now ready: We can now define the material to be applied to our mesh. This is important because depending on the material strength, our object will react differently to forces applied to it. Select the analysis object, and press the New Material button. A task panel will open to allow us to choose a material. In the Material drop-down list, choose the Concrete-generic material, and press the OK button. We are now ready to apply forces. Let's start by specifying which faces are fixed into the ground and can therefore not move. Press the Constraint fixed button. Click on the bottom face of our building and press the OK button. The bottom face is designated as unmovable: We will now add a load on the top face, that could represent, for example, a massive weight being placed on the roof. For this we will use a pressure constraint. Press the Constraint pressure button. Click the top face of the roof, set the pressure to 10MPa (the pressure is applied by square millimeter) and press the OK button. Our force is now applied: We are now ready to start the calculation. Select the CalculiX object in the tree view, and press the Start Calculation button. In the task panel that will open, click first the Write .inp file button to create the input file for CalculiX, then the Run CalculiX button. A few moments later, the calculation will be done: We can now look at the results. Close the task panel, and see that a new Results object has been added to our analysis. Double-click the Results object Set the type of result that you want to see on the mesh, for example "absolute displacement", tick the show checkbox under Displacement, and move the slider next to it. You will be able to see the deformation growing as you apply more force: The results displayed by the FEM workbench are of course currently not enough to perform real-life decisions about structures dimensioning and materials. However, they can already give precious information about how the forces flow through a structure, and which are the weak areas that will feel the most stress. Downloads The file created during this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/fem.FCStd Read more The FEM Workbench Installing required FEM components CalculiX NetGen


Manual:Creating renderings

+Fortunately, the open source world offers many applications to produce realistic images. The most famous one is probably Blender, which is very popular, and widely used in the film and gaming industries. 3D models can very easily and faithfully be exported from FreeCAD and imported into Blender, where you can add realistic materials and illumination, and produce the final images or even animations. Some other open source rendering tools are made to be used inside other applications, and will take care of doing the complex calculations to produce realistic images. Through its Raytracing Workbench, FreeCAD can use two of these rendering tools: POV-Ray and Luxrender. POV-Ray is a very old project, and is considered a classical raytracing engine, while Luxrender is much newer, and is categorized as an unbiased renderer. Both have their strengths and weaknesses, depending on the type of image one wants to render. The best way to know is to look at examples on each engine's website.

Installation

Before being able to use the Raytracing Workbench in FreeCAD, one of these two rendering applications needs to be installed on your system. This is usually very straightforward. They both provide installers for many platforms or are usually included in the software repositories of most Linux distributions. Once POV-Ray or Luxrender is installed, we need to set the path to their main executable in the FreeCAD preferences. This is usually only required on Windows and Mac. On Linux, FreeCAD will pick it from the standard locations. The location of the povray or luxrender executables can be found by searching your system for files named povray (or povray.exe on Windows) and luxrender (or luxrender.exe on Windows). In this preferences screen we can also set the desired image size we want to produce.

Rendering with PovRay

We will use the table we have been modelling in the traditional modeling chapter to produce renderings with PovRay and Luxrender. Start by loading the table.FCStd file that we modelled earlier or from the link at the bottom of this chapter. Press the small down arrow next to the New Povray project button, and choose the RadiosityNormal template A warning message might appear telling you that the current 3D view is not in perspective mode and the rendering will therefore differ. Correct this by choosing No, choosing menu View->Perspective view and choosing the RadiosityNormal template again. You can also try other templates after you create a new project, simply by editing its Template property. A new project has now been created: The new project has adopted the point of view of the 3D view as it was at the moment we pressed the button. We can change the view, and update the view position stored in the Povray project anytime, by pressing the Reset camera button. The Raytracing Workbench works the same way as the Drawing Workbench: Once a project folder is created, we must add Views of our objects to it. We can now do that by selecting all the objects that compose the table, and press the Insert part button: The views have taken the color and transparency values from their original parts, but you can change that in the properties of each individual view if you wish. We are now ready to produce our first Povray render. Press the Render button. Note for windows users: when receiving (in Povray) a warning saying "I/O restrictions prohibit write access ..." open Povray choose "Options > Script I/O Restrictions" and make sure it is set to "No Restrictions" retry render You will be asked to give a file name and path for the .png image that will be saved by Povray. Povray will then open and calculate the image. When this is done, click the image to close the Povray window. The resulting image will be loaded in FreeCAD:

Rendering with LuxRender

Rendering with Luxrender works almost the same way. We can leave our file open and create a new Luxrender project in the same file, or reload it to start from scratch. Press the little down arrow next to the New Luxrender project button and choose the LuxOutdoor template. Select all the components of the table. If you still have the Povray project in your document, be sure to also select the Luxrender project itself, so the views created in the next step won't go in the wrong project by mistake. Press the Insert part button. Select the Luxrender project, and press the Render button. Luxrender works differently to Povray. When you start the render, the Luxrender application will open and immediately start rendering: If you leave that window open, Luxrender will continue calculating and rendering forever, progressively refining the image. It is up to you to decide when the image has reached a sufficient quality for your needs, and stop the render. There are also many controls to play with, on the left panel. All these controls will change the aspect of the image being rendered on the fly, without stopping the rendering. When you feel the quality is good enough, press Render->stop, and then File->Export to image->Tonemapped low dynamic range to save the rendered image to a png file. You can greatly extend the rendering possibilities of FreeCAD by creating new templates for Povray or Luxrender. This is explained in the Raytracing Workbench documentation. Downloads The table model: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/table.FCStd The file produced during this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/render.FCStd Read more The Raytracing Workbench Blender POV-Ray Luxrender


Manual:A gentle introduction

But the Python console has another very important use: Every time you press a toolbar button, or perform other operations in FreeCAD, some Python code is printed in the console and executed. By leaving the Python console open, you can literally see the Python code unfold as you work, and in no time, almost without knowing it, you will learning some of the Python language. FreeCAD also has a macros system, which allows you to record actions to be replayed later. This system also uses the Python console, by simply recording everything that is done in it. In this chapter, we will discover very generally the Python language. If you are interested in learning more, the FreeCAD documentation wiki has an extensive section related to Python programming.

Writing Python code

There are two easy ways to write Python code in FreeCAD: From the Python console (menu View -> Panels -> Python Console), or from the Macro editor (menu Tools -> Macros -> New). In the console, you write Python commands one by one, which are executed when you press return, while the macros can contain a more complex script made of several lines, which is executed only when the macro is launched from the same Macros window. In this chapter, you will be able to use both methods, but it is highly recommended to use the Python Console, since it will immediately inform you of any errors you make while typing. If this is your first time using Python, consider reading this short introduction to Python programming before going any further, it will make the basic concepts of Python clearer.

Manipulating FreeCAD objects

Let's start by creating a new empty document: doc = FreeCAD.newDocument() If you type this in the FreeCAD Python console, you will notice that as soon as you type "FreeCAD." (the word FreeCAD followed by a dot), a windows pops up, allowing to quickly autocomplete the rest of your line. Even better, each entry in the autocomplete list has a tooltip explaining what it does. This makes it very easy to explore the functionality available. Before choosing "newDocument", have a look at the other options available. As soon as you press Enter our new document will be created. This is similar to pressing the "new document" button on the toolbar. In Python, the dot is used to indicate something that is contained inside something else (newDocument is a function that is inside the FreeCAD module). The window that pops up therefore shows you everything that is contained inside "FreeCAD". If you would add a dot after newDocument, instead of the parentheses, it would show you everything that is contained inside the newDocument function. The parentheses are mandatory when you are calling a Python function, such as this one. We will illustrate that better below. Now let's get back to our document. Let's see what we can do with it. Type the following and explore the available options: doc. Usually names that begin with an upper-case letter are attributes: they contain a value. Names that begin with a lower-case letter are functions (also called methods): they "do something". Names that begin with an underscore are usually there for the internal use of the module, and you should ignore them. Let's use one of the methods to add a new object to our document: box = doc.addObject("Part::Box","myBox") Our box is added in the tree view, but nothing happens in the 3D view yet, because when working from Python, the document is never recomputed automatically. We must do that manually, whenever required: doc.recompute() Now our box has appeared in the 3D view. Many of the toolbar buttons that add objects in FreeCAD actually do two things: add the object, and recompute. If you turned on the "show script commands in Python console" option above, try now adding a sphere with the appropriate button in the Part Workbench, and you will see the two lines of Python code being executed one after the other. You can get a list of all possible object types like Part::Box: doc.supportedTypes() Now let's explore the contents of our box: box. You'll immediately see a couple of very interesting things such as: box.Height This will print the current height of our box. Now let's try to change that: box.Height = 5 If you select your box with the mouse, you will see that in the properties panel, under the Data tab, our Height property appears with the new value. All properties of a FreeCAD object that appear in the Data and View tabs are directly accessible by Python too, by their names, like we did with the Height property. Data properties are accessed directly from the object itself, for example: box.Length View properties are stored inside a ViewObject. Each FreeCAD object possesses a ViewObject, which stores the visual properties of the object. When running FreeCAD without its Graphical Interface (for example when launching it from a terminal with the -c command line option, or using it from another Python script), the ViewObject is not available, since there is no visual at all. Try the following example to access the line color of our box: box.ViewObject.LineColor

Vectors and Placements

Vectors are a fundamental concept in any 3D application. It is a list of 3 numbers (x, y and z), describing a point or position in the 3D space. A lot of things can be done with vectors, such as additions, subtractions, projections and much more. In FreeCAD vectors work like this: myvec = FreeCAD.Vector(2,0,0) print(myvec) print(myvec.x) print(myvec.y) othervec = FreeCAD.Vector(0,3,0) sumvec = myvec.add(othervec) Another common feature of FreeCAD objects is their Placement. As we saw in earlier chapters, each object has a Placement property, which contains the position (Base) and orientation (Rotation) of the object. These properties are easy to manipulate from Python, for example to move our object: print(box.Placement) print(box.Placement.Base) box.Placement.Base = sumvec otherpla = FreeCAD.Placement() otherpla.Base = FreeCAD.Vector(5,5,0) box.Placement = otherpla Read more Python Macros Introduction to Python Python scripting tutorial Power users hub


Manual:Creating and manipulating geometry

So the first thing we need to do to work with Part geometry, is to do the Python equivalent to switching to the Part Workbench: import the Part module: import Part Take a minute to explore the contents of the Part module, by typing Part. and browsing through the different methods available. The Part module offers several convenience functions such as makeBox, makeCircle, etc... which will instantly build an object for you. Try this, for example: Part.makeBox(3,5,7) When you press Enter after typing the line above, nothing will appear in the 3D view, but something like this will be printed on the Python Console: <Solid object at 0x5f43600> This is where an important concept takes place. What we created here is a Part Shape. It is not a FreeCAD document object (yet). In FreeCAD, objects and their geometry are independent. Think of a FreeCAD document object as a container, that will host a shape. Parametric objects will also have properties such as Length and Width, and will recalculate their Shape on-the-fly, whenever one of the properties changes. What we did here is calculate a shape manually. We can now easily create a "generic" document object in the current document (make sure you have at least one new document open), and give it a box shape like the one we just made: boxShape = Part.makeBox(3,5,7) myObj = FreeCAD.ActiveDocument.addObject("Part::Feature","MyNewBox") myObj.Shape = boxShape FreeCAD.ActiveDocument.recompute() Note how we handled myObj.Shape , notice that it is done exactly like we did it in the previous chapter, when we changed other properties of an object, such as box.Height = 5 . In fact, Shape is also a property, just like Height. Only it takes a Part Shape, not a number. In the next chapter we will have a better look at how these parametric objects are constructed. For now, let's explore our Part Shapes in more detail. At the end of the chapter about traditional modeling with the Part Workbench we showed a table that explains how Part Shapes are constructed, and their different components (Vertices, edges, faces, etc). The exact same components exist here and can be retrieved from Python. Part Shapes always have the following attributes: Vertexes, Edges, Wires, Faces, Shells and Solids. All of them are lists, that can contain any number of elements or be empty: print(boxShape.Vertexes) print(boxShape.Edges) print(boxShape.Wires) print(boxShape.Faces) print(boxShape.Shells) print(boxShape.Solids) For example, let's find the area of each face of our box shape above: for f in boxShape.Faces: print(f.Area) Or, for each edge, its start point and end point: for e in boxShape.Edges: print("New edge") print("Start point:") print(e.Vertexes[0].Point) print("End point:") print(e.Vertexes[1].Point) As you see, if our boxShape has a "Vertexes" attribute, each Edge of the boxShape also has a "Vertexes" attribute. As we can expect, the boxShape will have 8 vertices, while the edge will only have 2, which are both part of the list of 8. We can always check what is the type of a shape: print(boxShape.ShapeType) print(boxShape.Faces[0].ShapeType) print(boxShape.Vertexes[2].ShapeType) So to resume the topic of Part Shapes: Everything starts with Vertices. With one or two vertices, you form an Edge (full circles have only one vertex). With one or more Edges, you form a Wire. With one or more closed Wires, you form a Face (the additional Wires become "holes" in the Face). With one or more Faces, you form a Shell. When a Shell is fully closed (watertight), you can form a Solid from it. And finally, you can join any number of Shapes of any types together, which is then called a Compound. We can now try creating complex shapes from scratch, by constructing all their components one by one. For example, let's try to create a volume like this: We will start by creating a planar shape like this: First, let's create the four base points: V1 = FreeCAD.Vector(0,10,0) V2 = FreeCAD.Vector(30,10,0) V3 = FreeCAD.Vector(30,-10,0) V4 = FreeCAD.Vector(0,-10,0) Then we can create the two linear segments: L1 = Part.LineSegment(V1,V2) L2 = Part.LineSegment(V4,V3) Note that we didn't need to create Vertices. We could immediately create Part.LineSegments from FreeCAD Vectors. This is because here we haven't created Edges yet. A Part.LineSegment (as well as Part.Circle, Part.Arc, Part.Ellipse or Part.BSpline) does not create an Edge, but rather a base geometry on which an Edge will be created. Edges are always made from such a base geometry, which is stored in its Curve attribute. So if you have an Edge, doing: print(Edge.Curve) will show you what kind of Edge it is, i.e. if it's based on a line, an arc, etc... But let's come back to our exercise, and build the arc segments. For this, we will need a third point, so we can use the convenient Part.Arc, which takes 3 points: VC1 = FreeCAD.Vector(-10,0,0) C1 = Part.Arc(V1,VC1,V4) VC2 = FreeCAD.Vector(40,0,0) C2 = Part.Arc(V2,VC2,V3) Now we have 2 lines (L1 and L2) and 2 arcs (C1 and C2). We need to turn them into edges: E1 = Part.Edge(L1) E2 = Part.Edge(L2) E3 = Part.Edge(C1) E4 = Part.Edge(C2) Alternatively, base geometries also have a toShape() function that do exactly the same thing: E1 = L1.toShape() E2 = L2.toShape() ... Once we have a series of Edges, we can now form a Wire, by giving it a list of Edges. We do need to take care of the order. W = Part.Wire([E1,E4,E2,E3]) And we can check if our Wire was correctly understood, and that it is correctly closed: print( W.isClosed() ) Which will print "True" or "False". In order to make a Face, we need closed Wires, so it is always a good idea to check that before creating the Face. Now we can create a Face, by giving it a single Wire (or a list of Wires if we want holes): F = Part.Face(W) Then we extrude it: P = F.extrude(FreeCAD.Vector(0,0,10)) Note that P is already a Solid: print(P.ShapeType) This is because when we extrude a single Face, we always get a Solid. This wouldn't be the case, for example, if we had extruded the Wire instead: S = W.extrude(FreeCAD.Vector(0,0,10)) print(s.ShapeType) Which will of course give us a hollow shell, with the top and bottom faces missing. Now that we have our final Shape, we are anxious to see it on screen! So let's create a generic object, and assign our new Solid to it: myObj2 = FreeCAD.ActiveDocument.addObject("Part::Feature","My_Strange_Solid") myObj2.Shape = P FreeCAD.ActiveDocument.recompute() Alternatively, the Part module also provides a shortcut that does the above operation quicker (but you cannot choose the name of the object): Part.show(P) All of the above, and much more, is explained in detail on the Part Scripting page, together with examples. Read more: The Part Workbench Part scripting


Manual:Creating parametric objects

class myParametricObject: def __init__(self,obj): obj.Proxy = self obj.addProperty("App::PropertyFloat","MyLength") ... def execute(self,obj): print ("Recalculating the shape...") print ("The value of MyLength is:") print (obj.MyLength) ... All Python classes usually have an __init__ method. What is inside that method is executed when that class is instantiated (which means, in programming slang, that a Python Object is created from that class. Think of a class as a "template" to create live copies of it). In our __init__ function here, we do two important things: 1- store our class itself into the "Proxy" attribute of our FreeCAD document object, that is, the FreeCAD document object will carry this code, inside itself, and 2- create all the properties our object needs. There are many types of properties available, you can get the full list by typing this code: FreeCAD.ActiveDocument.addObject("Part::FeaturePython","dummy").supportedProperties() Then, the second important part is the execute method. Any code in this method will be executed when the object is marked to be recomputed, which will happen when a property has been changed. That is all there is to it. Inside execute, you need to do all that needs to be done, that is, calculating a new shape, and attributing to the object itself with something like obj.Shape = myNewShape. That is why the execute method takes an "obj" argument, which will be the FreeCAD document object itself, so we can manipulate it inside our python code. One last thing is important to remember: When you create such parametric objects in a FreeCAD document, when you save the file, the python code above is not stored inside the file. This is for security reasons, if a FreeCAD file contained code, it would be possible for someone to distribute FreeCAD files containing malicious code that could harm other people's computers. So, if you distribute a file that contains objects made with the above code, such code must also be present on the computer that will open the file. The easiest way to achieve that is usually to save the code above in a macro, and distribute the macro together with your FreeCAD file, or share your macro on the FreeCAD macros repository where anybody can download it. Below, we will do a small exercise, building a parametric object that is a simple parametric rectangular face. More complex examples are available on the parametric object example and in the FreeCAD source code itself. We will give our object two properties: Length and Width, which we will use to construct a rectangle. Then, since our object will already have a pre-built Placement property (all geometric object have one by default, no need to add it ourselves), we will displace our rectangle to the location/rotation set in the Placement, so the user will be able to move the rectangle anywhere by editing the Placement property. class ParametricRectangle: def __init__(self,obj): obj.Proxy = self obj.addProperty("App::PropertyFloat","Length") obj.addProperty("App::PropertyFloat","Width") def execute(self,obj): # we need to import the FreeCAD module here too, because we might be running out of the Console # (in a macro, for example) where the FreeCAD module has not been imported automatically import Part,FreeCAD # first we need to make sure the values of Length and Width are not 0 # otherwise the Part.Line will complain that both points are equal if (obj.Length == 0) or (obj.Width == 0): # if yes, exit this method without doing anything return # we create 4 points for the 4 corners v1 = FreeCAD.Vector(0,0,0) v2 = FreeCAD.Vector(obj.Length,0,0) v3 = FreeCAD.Vector(obj.Length,obj.Width,0) v4 = FreeCAD.Vector(0,obj.Width,0) # we create 4 edges e1 = Part.Line(v1,v2).toShape() # Warning. Since FC v0.17, use Part.LineSegment instead of Part.Line e2 = Part.Line(v2,v3).toShape() e3 = Part.Line(v3,v4).toShape() e4 = Part.Line(v4,v1).toShape() # we create a wire w = Part.Wire([e1,e2,e3,e4]) # we create a face f = Part.Face(w) # All shapes have a Placement too. We give our shape the value of the placement # set by the user. This will move/rotate the face automatically. f.Placement = obj.Placement # all done, we can attribute our shape to the object! obj.Shape = f Instead of pasting the above code in the Python console, we'd better save it somewhere, so we can reuse and modify it later. For example in a new macro (menu Tools -> Macros -> Create). Name it, for example, "ParamRectangle". However, FreeCAD macros are saved with a .FCMacro extension, which Python doesn't recognize when using import . So, before using the above code, we will need to rename the ParamRectangle.FCMacro file to ParamRectangle.py. This can be done simply from your file explorer, by navigating to the Macros folder indicated in menu Tools -> Macros. Once that is done, we can now do this in the Python Console: import ParamRectangle By exploring the contents of ParamRectangle, we can verify that it contains our ParametricRectangle class. To create a new parametric object using our ParametricRectangle class, we will use the following code. Observe that we use Part::FeaturePython instead of Part::Feature that we have been using in the previous chapters (The Python version allows to define our own parametric behaviour): myObj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Rectangle") ParamRectangle.ParametricRectangle(myObj) myObj.ViewObject.Proxy = 0 # this is mandatory unless we code the ViewProvider too FreeCAD.ActiveDocument.recompute() Nothing will appear on screen just yet, because the Length and Width properties are 0, which will trigger our "do-nothing" condition inside execute. We just need to change the values of Length and Width, and our object will magically appear and be recalculated on-the-fly. Of course it would be tedious to have to type these 4 lines of Python code each time we want to create a new parametric rectangle. A very simple way to solve this is placing the 4 lines above inside our ParamRectangle.py file, at the end, after the end of the ParametricRectange class (We can do this from the Macro editor). Now, when we type import ParamRectangle , a new parametric rectangle will automatically be created. Even better, we can add a toolbar button that will do just that: Open menu Tools -> Customize Under the "Macros" tab, select our ParamRectangle.py macro, fill in the details as you wish, and press "Add": Under the Toolbars tab, create a new custom toolbar in the workbench of your choice (or globally), select your macro and add it to the toolbar: That's it, we now have a new toolbar button which, when clicked, will create a parametric rectangle. Remember, if you want to distribute files created with this new tool to other people, they must have the ParamRectangle.py macro installed on their computer too. Read more The FreeCAD macros repository Parametric object example More examples in the FreeCAD code


Manual:Creating interface tools

Python offers a basic tool to have the user enter text on screen: text = raw_input("Height of the rectangle?") print("The entered height is ",text) However, this requires a running Python console, and when running our code from a macro, we are not always sure that the Python console will be turned on on the user's machine. The Graphical User Interface, or GUI, that is, all the part of FreeCAD that is displayed on your screen (the menu, toolbars, 3D view, etc), is all there for that purpose: interact with the user. FreeCAD's interface is built with Qt, a very common open source GUI toolkit that offers a wide range of tools such as dialog boxes, buttons, labels, text input boxes or pull-down menus. These are all generically called "widgets". The Qt tools are very easy to use from Python, thanks to a Python module called Pyside (there are several other Python modules to communicate with Qt from Python too). This module allows you to create and interact with widgets, read what the user did with them (what was filled in text boxes) or do things when, for example, a button was pressed. Qt also provides another interesting tool called Qt Designer, which is today embedded inside a bigger application called Qt Creator. It allows to design dialog boxes and interface panels graphically, instead of having to code them manually. In this chapter, we will use Qt Creator to design a panel widget that we will use in the Task panel of FreeCAD. So you will need to download and install Qt Creator from its official page if you are on Windows or Mac (on Linux it will usually be available from your software manager application). In the following exercise, we will first create a panel with Qt Creator that asks for length, width and height values, then we will create a Python class around it, that will read the values entered by the user from the panel, and create a box with the given dimensions. This Python class will then be used by FreeCAD to display and control the task panel: Let's start by creating the widget. Start Qt Creator, then menu File → New File or Project → Files and Classes → Qt → Qt Designer Form → Dialog without buttons. Click Next, give it a filename to save, click Next, leave all project fields to their default value ("<none>"), and Create. FreeCAD's Task system will automatically add OK/Cancel buttons, that's why we chose here a dialog without buttons. Find the Label in the list in the left panel, and drag it onto the canvas of our widget. Double-click the recent placed Label, and change its text to Length. Right-click the widget canvas, and choose Lay out → Lay out in a Grid. This will turn our widget into a grid with currently only one cell, occupied by ourfirst label. We can now add the next items at the left, right, top or bottom of our first label, and the grid will expand automatically. Add two more labels below the first one, and change their text to Width and Height: Now place 3 Double Spin Box widgets next to our Length, Width and Height labels. For each of them, in the lower right panel, which shows all the available settings for the selected widget, locate Suffix and set their suffix to mm. FreeCAD has a more advanced widget, that can handle different units, but that is not available in Qt Creator by default (but can be compiled), so for now we will use a standard Double Spin Box, and we add the "mm" suffix to make sure the user knows in which units they work: Now our widget is done, we just need to make sure of one last thing. Since FreeCAD will need to access that widget and read the Length, Width and Height values, we need to give proper names to those widgets, so we can easily retrive them from within FreeCAD. Click each of the Double Spin Boxes, and in the upper right window, double-click their Object Name, and change them to something easy to remember, for example: BoxLength, BoxWidth and BoxHeight: Save the file, you can now close Qt Creator, the rest will be done in Python. Open FreeCAD and create a new macro from menu Macro → Macros → Create Paste the following code. Make sure you change the file path to match where you saved the .ui file created in QtCreator: import FreeCAD,FreeCADGui,Part # CHANGE THE LINE BELOW path_to_ui = "C:\Users\yorik\Documents\dialog.ui" class BoxTaskPanel: def __init__(self): # this will create a Qt widget from our ui file self.form = FreeCADGui.PySideUic.loadUi(path_to_ui) def accept(self): length = self.form.BoxLength.value() width = self.form.BoxWidth.value() height = self.form.BoxHeight.value() if (length == 0) or (width == 0) or (height == 0): print("Error! None of the values can be 0!") # we bail out without doing anything return box = Part.makeBox(length,width,height) Part.show(box) FreeCADGui.Control.closeDialog() panel = BoxTaskPanel() FreeCADGui.Control.showDialog(panel) In the code above, we used a convenience function (PySideUic.loadUi) from the FreeCADGui module. That function loads a .ui file, creates a Qt Widget from it, and maps names, so we can easily access the subwidget by their names (ex: self.form.BoxLength). The "accept" function is also a convenience offered by Qt. When there is an "OK" button in a dialog (which is the case by default when using the FreeCAD Tasks panel), any function named "accept" will automatically be executed when the "OK" button is pressed. Similarly, you can also add a "reject" function which gets executed when the "Cancel" button is pressed. In our case, we omitted that function, so pressing "Cancel" will do the default behaviour (do nothing and close the dialog). If we implement any of the accept or reject functions, their default behaviour (do nothing and close) will not occur anymore. So we need to close the Task panel ourselves. This is done with: FreeCADGui.Control.closeDialog() Once we have our BoxTaskPanel that has 1- a widget called "self.form" and 2- if needed, accept and reject functions, we can open the task panel with it, which is done with these two last lines: panel = BoxTaskPanel() FreeCADGui.Control.showDialog(panel) Note that the widget created by PySideUic.loadUi is not specific to FreeCAD, it is a standard Qt widget which can be used with other Qt tools. For example, we could have shown a separate dialog box with it. Try this in the Python Console of FreeCAD (using the correct path to your .ui file of course): from PySide import QtGui w = FreeCADGui.PySideUic.loadUi("C:\Users\yorik\Documents\dialog.ui") w.show() Of course we didn't add any "OK" or "Cancel" button to our dialog, since it was made to be used from the FreeCAD Task panel, which already provides such buttons. So there is no way to close the dialog (other than pressing its Window Close button). But the function show() creates a non-modal dialog, which means it doesn't block the rest of the interface. So, while our dialog is still open, we can read the values of the fields: w.BoxHeight.value() This is very useful for testing. Finally, don't forget there is much more documentation about using Qt widgets on the FreeCAD Wiki, in the Python Scripting section, which contains a dialog creation tutorial, a special 3-part PySide tutorial that covers the subject extensively.


Manual:The Community

The forum is also a great place to show what you achieved with FreeCAD, to help newcomers when you are more experienced, and to follow and give your opinions in more technical discussions about development. All the FreeCAD development is discussed on the forum, and anybody is free to read or participate. There are also FreeCAD communities forming outside of the FreeCAD forum, for example on Facebook. If you are becoming as enthusiastic about FreeCAD as we are, you might want to help the project. This can be done in many different ways, and there are tasks for everybody, programmers and non-programmers, for example: Help to spread the word: Many people would get huge benefit from using a free, open source 3D modeler like FreeCAD, but simply don't know its existence. Publishing the work you do with FreeCAD, talking about it on social networks, etc... helps these people to discover FreeCAD. Help newcomers: The vast majority of discussions on the forum are questions asked by new users. You might know good anwers to give them. Help reporting bugs: The stablility of FreeCAD comes in large part from the fixing of bugs. Since it is not possible for the FreeCAD developers to test all possible use cases, it is important that users report problems when they detect them. Be sure to read the guidelines if you think you found a bug, and then write a report on the bug tracker. Help to write documentation: The FreeCAD documentation wiki is also written by community members. Some sections of it are still incomplete, or their information incorrect or obsolete. You might be able to help to fix that. To be able to work on the wiki, you will need to familiarize yourself with wiki editing, and ask permission to edit the FreeCAD wiki on the forum. Help to translate FreeCAD: The translation of FreeCAD is done online by community members, on crowdin. If you don't see your language there, ask one of the administrators to have it added. Help to translate the wiki documentation: Every page of the wiki is translatable, and requires very little knowledge of the wiki syntax. Helping with translation is also a great way to learn FreeCAD. Write scripts and macros: FreeCAD has a growing list of Macros. If you wrote some interesting functionality, consider sharing it there. Programming: For this, you need to know how to program in Python or C++, and have a good knowledge of FreeCAD itself. The source code of FreeCAD is located on the Github account of the FreeCAD project. Anybody can download, use and modify the code. You can publish your modifications (on Github or any other Git hosting service). If you made interesting modifications, that you wish to see included in the FreeCAD source code, you must ask the community to have them included. This can be done using Github's pull requests mechanism, but the very best way is to discuss what you intend to do first on the forum, and then post an official request in the Pull requests section of the forum when your code is ready. This avoids that you work on something that someone else is already working on too, and ensures that others agree with the way you are doing it, so there is no risk of having your work refused for some reason you didn't foresee. Hopefully, we managed to give you a good taste of FreeCAD in this manual, and you are already our newest community member. Welcome!


Tutorials

This page presents a selection of high quality written tutorials. A complete, unsorted list of tutorials can be found in Category:Tutorials, a complete and sortable one can be found in the table below. Also visit video tutorials and offsite tutorials for tutorials hosted on external sites. A useful source of video tutorials is YouTube. If you'd like to contribute with writing wiki documentation and tutorials, see the general wiki guidelines in WikiPages, and read the tutorial guidelines. Please notice the version of FreeCAD used in the tutorial as some tutorials may use an old version of the program. Although the general modelling process may still work, some tools may have changed.

Architecture and BIM

Arch tutorial (v0.14) This is the essential introduction to the Arch Workbench. It is extensive and showcases a typical workflow, from importing plans in DXF format to building the 3D model. BIM modeling How to model a small house, produce a blueprint with TechDraw, and export to IFC. Open windows and doors (v0.18) How to display windows and doors as open, with elevation and plan symbols, and produce a basic floor plan with TechDraw. Design custom windows (v0.18) How to draw custom doors and windows using the Sketcher, and adjust their normals to correctly place them in walls. Arch panel tutorial (v0.15) Modeling a microhouse roof panel by using the Sketcher, the Window tool, and the Panel tool. WikiHouse modelling Re-modeling the WikiHouse project using sketches and panels, starting from importing a mesh model created in SketchUp.

Modeling parts

FreeCAD provides two main workflows to modeling parts: combining objects, a method called Constructive solid geometry (CSG) using the Part Workbench, and using parametric modelling and feature editing with the PartDesign Workbench. Please note that the PartDesign Workbench workflow was considerably changed from FreeCAD 0.17 onward; some of the tutorials haven't been updated and may refer to the 0.16 version. Creating a simple part with PartDesign (v0.17) An introduction to the PartDesign workflow: tracing a sketch, using pad, pocket, and moving the object. Basic Part Design Tutorial (v0.17) Model a simple part using a feature editing methodology: creating a sketch, using pad, external references, pocket, and mirror. Model an electric toothbrush head stand (v0.16) Multiple features used: sketch, distance and coincident constraints, pad, external references, fillet, chamfer, linear pattern, and draft. Modeling for product design (v0.16) Modeling a Lego block: sketches, vertical and horizontal distance constraints, pad, pocket, external reference, linear pattern, and assembly. Traditional modeling, the CSG way Modeling a table by using simple solids like cubes and cylinders, and performing boolean operations (fusions and cuts) with them. Draft ShapeString tutorial (v0.19) Create engraved text on a solid: extrude a shapestring to make it solid, then use a boolean cut to carve it from another solid. Create a wiffle ball (v0.19) Use solid primitives, like cubes and cylinders, and boolean operations, like union and cut, to create a hollowed ball. Basic modeling tutorial Create an iron angle by two methods: using solid primitives, and boolean operations (CSG); and by extruding a planar profile. Aeroplane tutorial Understand placements in FreeCAD by creating a simple aeroplane model. Then learn about rotation angles, yaw (Z), pitch (Y), and roll (X). Thread for screw tutorial (v0.19) Understand how to create threads with several techniques that include use of the tools Part Helix, PartDesign AdditivePipe, Part Sweep, Part Fuse, and Part Cut. The Raspberry Pi project has made simple tutorials that are easy to follow, particularly for those new to CAD systems: freecad-dice, model a die with six faces, and optionally 3D print it. freecad-headphone-tidy, model a spool to organize and store earphones, and optionally 3D print it. freecad-chess-set, model and entire chess set in Bauhaus modernist style. raspberrypilearning repository (CC-BY 4.0) with other examples.

Drafting and Sketching

Traditional 2D drafting Draw a floor plan with lines, wires, rectangles, circular arcs, and add hatch patterns, annotations, and dimensions. Export the result to DXF. Draft tutorial (v0.19) This is a basic introduction to the tools of the Draft Workbench: working plane, grid, line, arc, upgrade, rectangle, circle, polygon, arrays, dimensions, annotations, and shapestring. Sketcher reference (v0.18) This is a 70-page long PDF document that serves as a detailed manual for the Sketcher Workbench. It explains the basics of Sketcher usage, and goes into a lot of detail about the creation of geometrical shapes, and each of the constraints. Basic Sketcher Tutorial (v0.19) This is a basic introduction to the tools of the Sketcher Workbench: construction mode, line, circle, arc, constraints (equality, vertical, horizontal, tangential, distance, angle, radius). Sketcher constraints practices (v0.19) Learn to efficiently constrain a sketch. Prefer geometric constraints over datum constraints.

Technical Drawings

Basic TechDraw Tutorial (v0.17) This is the essential introduction to the tools of the TechDraw Workbench: page, view, scale, vertical and horizontal dimensions, annotations, projection groups, linking dimensions to the 3D view. Creating a new background template (v0.17) Instructions to create a page template in Inkscape for using it with the TechDraw Workbench. Determine the size of the sheet, draw a frame for the page, define fixed text, and editable text fields. Measurement Of Angles On Holes (v0.19) Instructions for adding center lines and subsequent angle representations on holes.

FEM

CalculiX cantilever FEM analysis (v0.17) This in an example included in every installation of FreeCAD; it demonstrates a basic analysis with the CalculiX FE solver. Purge the current result, re-run the solver, and view the displacements and stresses in the deformed mesh in the viewport. Simple FEM introduction (v0.17) This is a short introduction to the steps required to perform an analysis in the FEM Workbench: model your object, create a mesh, add constraints and forces, add a material, run the solver, and visualize the results. FEM shear analysis of a composite block (v0.17) Study the deformation of a block made of a hard nucleus surrounded by a softer material: create mesh regions, add materials, set up sliding constraints, add shear loads, run the solver, and visualize the results with a clip plane. Analysis of reinforced concrete with FEM (v0.19) Estimate the level of reinforcement required in a concrete structure to prevent brittle failure under tension or shear. Post-Processing of FEM results with Paraview (v0.19) This tutorial explains the basics of transferring data from the FEM Workbench to Paraview and shows some of the options and settings for displaying data.

CNC & 3D Printing

Path Workbench for the impatient This is a quick presentation of the workflow for the Path Workbench: create a job, define the output, define the milling tool, define the path operations, start the simulation, and generate a G-code output file. Preparing models for 3D printing (v0.16) Convert a solid object to a mesh object using the Mesh Workbench, export the mesh to STL format, and use Slic3r to prepare the G-code. Alternatively use the Cura Workbench or the Path Workbench to generate the G-code.

Rendering

Creating renderings Quickly produce a rendered image of your bodies with POV-Ray and LuxRender, if they are installed in your system. Raytracing tutorial (v0.16) Describes the basic workflow of the Raytracing Workbench using POV-Ray or LuxRender: set the path to the renderers, create a project, set the camera position, select the model, run the renderer. Intermediate FreeCAD and POV-ray tutorial (v0.18) Workflow to produce a better render with POV-Ray: create a project, add objects, set the camera, save the .pov file, manually edit the file to improve the textures, planes, lights, and then run the renderer. Rendering a FreeCAD assembly with Blender (v0.18) Export bodies from FreeCAD to Wavefront .obj, import the file into Blender, set up a simple Sun light, assign basic materials with the Principled BSDF shader, and produce a rendered image with EEVEE and Cycles.

Robot workbench

Development of the Robot Workbench is currently abandoned. Please inquire on our forum regarding any news or alternative workbenches. Robot tutorial (v0.17) Simulate the movement of an industrial robot: set up a trajectory, set up home position, change the robot position, insert various waypoints, and simulate the robot movement.

Scripting

These are tutorials that are related to scripting or programming. They are geared towards more experienced users, who are already somewhat familiar with the program. Python scripting tutorial How to install macros How to install additional workbenches

Tutorials - Comprehensive list

Here are listed all the tutorials that are not in the manual regardless of their quality. If a tutorial is listed in the Category:Tutorials and not in this table please insert it.
TutorialTopicLevelTime to complete hh:mmAuthorsFreeCAD versionExample files
Add FEM Constraint TutorialM42kus
Add FEM Equation TutorialJohnWang
AeroplanePart WorkbenchBeginner0:10Hughthecat
Analysis of reinforced concrete with FEMReinforced concrete with FEMIntermediate1:00HarryvL0.19 or above
Arch panel tutorialModeling an architectural panelBeginner1:00Yorik
Arch tutorialModelingIntermediateYorik0.14
Basic Attachment TutorialSketch attachmentBeginner/intermediate01:00Bance0.17 and aboveBasic Attachment Tutorial.FCStd
Basic modeling tutorialIntroduction to modellingBeginner0:15NormandCAnyNone
Basic Part Design TutorialModelingBeginnerMark Stephen (Quick61) and HarryGeier0.17 or aboveBasic Part Design for v0.17
Basic Sketcher TutorialSketcherBeginner1:00Drei and Vocx0.19Basic Sketcher tutorial
Basic TechDraw TutorialTechDraw WorkbenchBeginnerWandererFan0.17 and aboveBasic Part Design for v0.17 Sample Basic TechDraw Tutorial Sample
Code snippetsPythonBeginner
Creating a simple part with PartDesignModelingBeginner1:00GlouGlou0.17 or aboveCreating a simple PartDesign Body.FCStd
Customize ToolbarsBeginner0:05Mario52AnyNone
Draft ShapeString tutorialProduct DesignBeginner0:30r-frank and vocx0.17 and aboveDraft_Shapestring_Text
Draft tutorialDraftingBeginner0:30Drei and vocx0.19Draft tutorial updated
Drawing Template HowTo (obsolete)2D DraftingIntermediate1:00Mark Stephen (Quick61)0.14.3700 or aboveNone
Drawing tutorial (obsolete)Blueprints / DrawingsBeginner0:15Drei0.16 or above
Dxf Importer InstallIntermediate0:05Mario52AnyNone
Engine Block TutorialPart WorkbenchBeginner1:00Andrewbuck400.14.3700
Export to STL or OBJExport to STL or OBJBeginner0:20r-frank0.16.6703
Extend FEM ModuleM42kus
FEM CalculiX Cantilever 3DFinite Element AnalysisBeginner0:10Bernd0.16.6377 or above
FEM Shear of a Composite BlockFinite Element AnalysisBeginner/Intermediate0:300HarryvL0.17.12960 or above
FEM tutorialFinite Element AnalysisBeginner0:10Drei0.16.6700 or above
FEM Tutorial PythonFinite Element AnalysisIntermediate0:30Bernd0.18.15985 or above
FreeCAD-Ship s60 tutorialShip WorkbenchBeginner
FreeCAD-Ship s60 tutorial (II)Ship WorkbenchBeginner
How to install additional workbenchesProgrammingMedium programmer0:15r-frankAnyNone
How to install macrosProgrammingMedium programmer0:15Mario52AnyNone
Import from STL or OBJImport from STL or OBJBeginner0:30r-frank1.00.16.6703
Import OpenSCAD codeImport OpenSCAD codeBeginner0:30r-frank0.16.6704None
Import text and geometry from InkscapeImport text and geometry from InkscapeBeginner0:30r-frank0.16.6704
Import/Export IFC - compiling IfcOpenShellArch WorkbenchAdvanced2:00Pablo Gil
Measurement Of Angles On HolesTechDraw WorkbenchBeginner0:01AnHi0.19
PartDesign Bearingholder Tutorial IProduct design - Bearingholder #1Beginner60 minutesNormandC
PartDesign Bearingholder Tutorial IIProduct design - Bearingholder #2Beginner60 minutesNormandC
PartDesign tutorialSketcherBeginner0:15Drei0.16 or above
Path Walkthrough for the ImpatientPath WorkbenchChrisb
Plot Basic tutorialPlot Workbench Basic TutorialBeginner
Plot MultiAxes tutorialPlot workbenchIntermediate
Post-Processing of FEM Results with ParaviewPost-Processing of FEM Results with ParaViewIntermediate2:00HarryvL0.19Beam and wall
Python scripting tutorialProgrammingIntermediate
Raytracing tutorialRaytracingBeginner0:010Drei0.16 or above
Robot 6-AxisRobot WorkbenchIntermediate
Robot tutorialRobot WorkbenchBeginnerr-frank
Scripted Parts: Ball Bearing - Part 1Part Scripting - Ball Bearing #1Beginner0:30r-frank0.16.6706
Scripted Parts: Ball Bearing - Part 2Part Scripting - Ball Bearing #2Beginner0:30r-frank0.16.6706
ScriptsScriptingBeginneronekk Carlo0.19
Sketcher Micro Tutorial - Constraint PracticesSketcherBeginner0:30Mark Stephen (Quick61) and vocx0.19Sketcher Constraints practices
Sketcher reference
Sketcher requirement for a sketchSketcherBeginnerMakerNone
Sketcher TutorialSketcherBeginnerUlrich
TechDraw pitch circle tutorialTechDraw WorkbenchBeginner0:10Andergrin0.19None
TechDraw TemplateHowToTechDraw WorkbenchIntermediate1:00wandererfan0.17None
Thread for Screw TutorialProduct designAdvanced1:00DeepSOIC, Murdic, vocx0.19Updated: Thread for screw tutorial
Toothbrush Head StandModelingBeginner1:00EmmanuelG0.16 or greaterThingiverse 2403310
Topological data scriptingProgrammingIntermediate
Transient FEM analysisTransient FEM analysis
Tutorial custom placing of windows and doorsArchitectureIntermediate1:00Vocx0.18 or aboveNone
Tutorial for open windowsArchitectureBeginner1:00Vocx0.18 or aboveNone
Tutorial FreeCAD POV rayRenderingIntermediate2:00Vocx0.18 or aboveNone
Tutorial Render with BlenderRenderingIntermediate1:00Vocx0.18 or aboveNone
VRML Preparation for Robot SimulationRobot WorkbenchIntermediate0.11.4252ppa1
WashersNone
Whiffle Ball tutorialProduct designBeginner0:30r-frank and vocx0.17 and aboveWhiffleBall_Tutorial_FCWiki.FCStd
Wikihouse porting tutorialWikihouse porting tutorialIntermediate/Advanced1:00


Workbenches

FreeCAD, like many modern design applications such as Revit or CATIA, is based on the concept of Workbench. A workbench can be considered as a set of tools specially grouped for a certain task. In a traditional furniture workshop, you would have a work table for the person who works with wood, another one for the one who works with metal pieces, and maybe a third one for the guy who mounts all the pieces together. In FreeCAD, the same concept applies. Tools are grouped into workbenches according to the tasks they are related to. When you switch from one workbench to another, the tools available on the interface change. Toolbars, command bars and possibly other parts of the interface switch to the new workbench, but the contents of your scene doesn't change. You could, for example, start drawing 2D shapes with the Draft Workbench, then work further on them with the Part Workbench. Note that sometimes a Workbench is referred to as a Module. However, Workbenches and Modules are different entities. A Module is any extension of FreeCAD, while a Workbench is a special type of Module with a GUI configuration (toolbars and menus).

Built-in workbenches

The following workbenches are bundled with every FreeCAD installation: Std Base. This is not really a workbench, but rather a category of 'standard' commands and tools that can be used in all workbenches. The Arch Workbench for working with architectural elements. The Draft Workbench contains 2D tools and basic 2D and 3D CAD operations. The FEM Workbench provides Finite Element Analysis (FEA) workflow. The Image Workbench for working with bitmap images. The Inspection Workbench is made to give you specific tools for examination of shapes. It is still under development. The Mesh Workbench for working with triangulated meshes. The OpenSCAD Workbench for interoperability with OpenSCAD and repairing constructive solid geometry (CSG) model history. The Part Workbench for working with CAD parts. The Part Design Workbench for building Part shapes from sketches. The Path Workbench is used to produce G-Code instructions. It is still under development. The Points Workbench for working with point clouds. The Raytracing Workbench for working with ray-tracing (rendering). The Reverse Engineering Workbench is intended to provide specific tools to convert shapes/solids/meshes into parametric FreeCAD-compatible features. It is still under development. The Robot Workbench for studying robot movements. The Sketcher Workbench for working with geometry-constrained sketches. The Spreadsheet Workbench for creating and manipulating spreadsheet data. The Start Center Workbench allows you to quickly jump to one of the most common workbenches. The Surface Workbench provides tools to create and modify surfaces. It is similar as the Part Shape builder Face from edges. The TechDraw Workbench for producing technical drawings from 3D models. It is the successor of the Drawing Workbench. The Test Framework Workbench is for debugging FreeCAD. The Web Workbench provides you with a browser window instead of the 3D view within FreeCAD.

Deprecated

The following workbenches are still included in the base installation for compatibility purposes, but they should no longer be used. The Complete Workbench holds all commands and features from all workbenches that met certain quality criteria. obsolete in version 0.17 The Drawing Workbench was used for producing technical drawings but has now been deprecated. It is still needed to read old FreeCAD files that contain objects created with this workbench. The TechDraw Workbench is its more advanced replacement. obsolete in version 0.17

External workbenches

FreeCAD workbenches are easy to program in Python, there are therefore many people developing additional workbenches outside of the FreeCAD main development area. The Addon manager. New workbenches are always in development, stay tuned!


Arch Workbench

Introduction

The Arch Workbench provides a modern building information modelling (BIM) workflow to FreeCAD, with support for features like fully parametric architectural entities such as walls, beams, roofs, windows, stairs, pipes, and furniture. It supports industry foundation classes ( TechDraw Workbench. The Arch Workbench imports all tools from the PartDesign. The BIM functionality of FreeCAD is now progressively split into this Arch Workbench, which holds basic architectural tools, and the Addon Manager. This BIM Workbench adds a new interface layer on top of the Arch tools, with the aim of making the BIM workflow more intuitive and user-friendly. See FreeCAD BIM migration guide. The developers of Draft, Arch, and BIM also collaborate with the greater OSArch community, with the ultimate goal of improving building design by using entirely free software.

Tools

These are tools for creating architectural objects. Wall: creates a wall from scratch or using a selected object as a base. Curtain Wall: creates a curtain wall from scratch or using a selected object as a base. introduced in version 0.19 Structural element: creates a structural element from scratch or using a selected object as a base. Rebar tools: the Reinforcement Addon augments the Arch Workbench Structures. Straight Rebar: creates a Straight reinforcement bar in a selected structural element. UShape Rebar: creates a UShape reinforcement bar in a selected structural element. LShape Rebar: creates a LShape reinforcement bar in a selected structural element. Bent Shape Rebar: creates a Bent Shape reinforcement bar in a selected structural element. Stirrup Rebar: creates a Stirrup reinforcement bar in a selected structural element. Helical Rebar: creates a Helical reinforcement bar in a selected structural element. ColumnReinforcement: creates a reinforcing bars inside a Column Arch Structure object. ColumnReinforcement TwoTiesSixRebars: creates a reinforcing bars inside a Column Arch Structure object. BeamReinforcement: creates reinforcing bars inside a Beam Arch Structure object. Rebar: creates a custom reinforcement bar in a selected structural element using a sketch. Floor: Creates a floor including selected objects Building Part: Creates a building part including selected objects Building: Creates a building including selected objects Site: Creates a site including selected objects Project: Creates a project including selected objects Reference: Links objects from another FreeCAD file into this document Window: Creates a window using a selected object as a base Section Plane: Adds a section plane object to the document Axis tools: The Axis tool allows you to places a series of axes in the current document. Axis: Adds a 1-direction array of axes to the document Axis System: Adds an axis system composed of several axes to the document Grid: Adds a grid-like object to the document Roof: Creates a sloped roof from a selected face Space: Creates a space object in the document Stairs: Creates a stairs object in the document Panel tools: Allows you to build all kinds of panel-like elements. Panel: Creates a panel object from a selected 2D object Panel Cut: Creates a 2D cut view from a panel introduced in version 0.17 Panel Sheet: Creates a 2D cut sheet including panel cuts or other 2D objects introduced in version 0.17 Nest: Allow to nest several flat objects inside a container shape introduced in version 0.17 Frame: Creates a frame object from a selected layout Fence: Creates a fence object from a selected post and path. introduced in version 0.19 Truss: Creates a truss from a selected line of from scratch. introduced in version 0.19 Equipment: Creates an equipment or furniture object Profile: Creates a parametric 2D profile. introduced in version 0.19 Pipe tools introduced in version 0.17 Pipe: Creates a pipe introduced in version 0.17 Pipe Connector: Creates a corner or tee connection between 2 or 3 selected pipes introduced in version 0.17 Material tools: The Material tools allows to add materials to the active document. Material: Creates a material and attributes it to selected objects, if any Multi-Material: Creates a multi-material and attributes it to selected objects, if any introduced in version 0.17 Schedule: Creates different types of schedules

Modification tools

These are tools for modifying architectural objects. Cut with a line: Cut an object according to a line. introduced in version 0.19 Cut with plane: Cut an object according to a plane. Add component: Adds objects to a component Remove component: Subtracts or removes objects from a component Survey: Enters or leaves surveying mode

Utilities

These are additional tools to help you in specific tasks. Component: Creates a non-parametric Arch component Clone component: Produces Arch Components that are clones of selected Arch objects (not to be confused with Draft Clone) Split Mesh: Splits a selected mesh into separate components Mesh To Shape: Converts a mesh into a shape, unifying coplanar faces Select non-solid meshes: Selects all non-solid meshes from the current selection or from the document Remove Shape: Turns cubic shape-based arch object fully parametric Close Holes: Closes holes in a selected shape-based object Merge Walls: Merge two or more walls Check: Check if the selected objects are solids and don't contain defects Ifc Explorer: Browse the contents of an IFC file Toggle IFC Brep flag: Forces a selected object to be exported as an IfcFacetedBrep. 3 Views from mesh: Creates top, frontal and side views from a mesh. Create IFC spreadsheet...: Creates a spreadsheet to store IFC properties of an object Toggle Subcomponents: Shows or hides the subcomponents of an Arch object.

Preferences

Preferences: preferences for the default appearance of walls, structures, rebars, windows, stairs, panels, pipes, grids and axes.

File formats

IFC: industry foundation classes DAE: Collada mesh format OBJ: Obj mesh format (export only) JSON: JavaScript Object Notation format (export only) 3DS: 3DS format (import only) SHP: GIS Shapefiles (import only)

API

The Arch module can be used in Python scripts and macros using the Arch Python API functions.

Tutorials

Architecture workflow: An example of how FreeCAD can begin to have its preliminary place in an architecture workflow. Arch tutorial (v0.14) Quick arch overview on Yorik's blog (v0.13) Video presentation of the Arch workbench (2016) Arch panel tutorial (v0.15) BIM modeling chapter from the FreeCAD manual Import from STL or OBJ Export to STL or OBJ


Draft Workbench

Introduction

The Draft Workbench is primarily focused on the creation and modification of 2D objects in FreeCAD. But it is not restricted to the XY plane of the global coordinate system. Its objects can have any orientation and position in 3D space, and some Draft objects can either be planar or non-planar. Draft objects can be used for general drafting, similar to what can be done with Inkscape or AutoCAD. But they can also form the base for the creation of 3D objects in other workbenches. A Draft Wire may define the path of an Arch Wall, a Draft Polygon can be extruded with Part Extrude, etc. Many of the Draft modifier tools can be applied to 2D and 3D objects created with other workbenches as well. You can, for example, move a Sketch or create a Draft OrthoArray from a Part object. The Draft Workbench also provides tools to define a working plane, a grid, and a snapping system to precisely control the position of geometry. If your primary goal is the production of complex 2D drawings and DXF files, and you don't need 3D modelling, FreeCAD may not be the right choice for you. You may wish to consider a dedicated software program for technical drafting instead, such as LibreCAD or QCad. The image shows the grid aligned with the XY plane.
On the left, in white, several planar objects.
On the right a non-planar Draft Wire used as the Path Object of a Draft PathArray.

Drafting

Line: creates a straight line. Polyline: creates a polyline, a sequence of several connected line segments. Fillet: creates a fillet, a rounded corner, or a chamfer, a straight edge, between two Draft Lines. introduced in version 0.19 Arc tools Arc: creates a circular arc from a center, a radius, a start angle and an aperture angle. Arc by 3 points: creates a circular arc from three points that define its circumference. introduced in version 0.19 Circle: creates a circle from a center and a radius. Ellipse: creates an ellipse from two points defining a rectangle in which the ellipse will fit. Rectangle: creates a rectangle from two points. Polygon: creates a regular polygon from a center and a radius. B-spline: creates a B-spline curve from several points. Bézier tools Cubic Bézier curve: creates a Bézier curve of the third degree. introduced in version 0.19 Bézier curve: creates a Bézier curve from several points. Point: creates a simple point. Facebinder: creates a surface object from selected faces. ShapeString: creates a compound shape that represents a text string. Hatch: creates hatches on the planar faces of a selected object. introduced in version 0.20

Annotation

Text: creates a multi-line text at a given point. Dimension: creates a linear dimension, a radial dimension or an angular dimension. Label: creates a multi-line text with a 2-segment leader line and an arrow. Annotation styles...: allows you to define styles that affect the visual properties of annotation-like objects. introduced in version 0.19

Modification

Move: moves or copies selected objects from one point to another. Rotate: rotates or copies selected objects around a center point by a given angle. Scale: scales or copies selected objects around a base point. Mirror: creates mirrored copies from selected objects. Offset: offsets each segment of a selected object over a given distance, or creates an offset copy of the selected object. Trimex: trims or extends a selected object. Stretch: stretches objects by moving selected points. Clone: creates linked copies, clones, of selected objects. Array tools Array: creates an orthogonal array from a selected object. It can optionally create a Link array. introduced in version 0.19 Polar array: creates an array from a selected object by placing copies along a circumference. It can optionally create a Link array. introduced in version 0.19 Circular array: creates an array from a selected object by placing copies along concentric circumferences. It can optionally create a Link array. introduced in version 0.19 Path array: creates an array from a selected object by placing copies along a path. Path Link array: idem, but create a Link array instead of a regular array. introduced in version 0.19 Point Array: creates an array from a selected object by placing copies at the points from a point compound. Point Link array: idem, but create a Link array instead of a regular array. introduced in version 0.19 Edit: puts selected objects in Draft Edit mode. In this mode the properties of objects can be edited graphically. Subelement highlight: temporarily highlights selected objects, or the base objects of selected objects. Join: joins Draft Lines and Draft Wires into a single wire. Split: splits a Draft Line or Draft Wire at a specified point or edge. Upgrade: upgrades selected objects. Downgrade: downgrades selected objects. Wire to B-spline: converts Draft Wires to Draft BSplines and vice versa. Draft to Sketch: converts Draft objects to Sketcher Sketches and vice versa. Set slope: slopes selected Draft Lines or Draft Wires by increasing, or decreasing, the Z coordinate of all points after the first one. Flip dimension: rotates the dimension text of selected Draft Dimensions 180° around the dimension line. Shape 2D view: creates 2D projections from selected objects.

Draft Tray

The Draft Tray allows selecting the working plane, defining style settings, toggling construction mode, and specifying the active layer or group. Select Plane. Set style. introduced in version 0.19 Toggle construction mode. AutoGroup: changes the active Draft Layer or, optionally, the active Std Group or group-like Arch object.

Draft annotation scale widget

With the Draft annotation scale widget the Draft annotation scale can be specified. introduced in version 0.19

Draft snap widget

The Draft snap widget can be used as an alternative for the Draft Snap toolbar. introduced in version 0.19

Draft Snap toolbar

The Draft Snap toolbar allows selecting the active snap options. The buttons belonging to active options stay depressed. For general information about snapping see: Draft Snap. Snap Lock: enables or disables snapping globally. Snap Endpoint: snaps to the endpoints of edges. Snap Midpoint: snaps to the midpoint of straight and circular edges. Snap Center: snaps to the center point of faces and circular edges, and to the DataPlacement point of Draft WorkingPlaneProxies and Arch BuildingParts. Snap Angle: snaps to the special cardinal points on circular edges, at multiples of 30° and 45°. Snap Intersection: snaps to the intersection of two edges. Snap Perpendicular: snaps to the perpendicular point on edges. Snap Extension: snaps to an imaginary line that extends beyond the endpoints of straight edges. Snap Parallel: snaps to an imaginary line parallel to straight edges. Snap Special: snaps to special points defined by the object. Snap Near: snaps to the nearest point on faces or edges. Snap Ortho: snaps to imaginary lines that cross the previous point at 0°, 45°, 90° and 135°. Snap Grid: snaps to the intersections of grid lines. Snap WorkingPlane: projects the snap point onto the current working plane. Snap Dimensions: shows temporary X and Y dimensions. Toggle Grid: switches the grid on or off.

Draft utility tools toolbar

Layer: creates a Draft Layer. introduced in version 0.19 Add a new named group: creates a named Std Group and moves selected objects to that group. introduced in version 0.20 Move to group...: moves objects to a Std Group. It can also ungroup objects. Select group: selects the content of Draft Layers, Std Groups or group-like Arch objects. Add to Construction group: moves objects to the Draft construction group. Toggle normal/wireframe display: switches the ViewDisplay Mode property of selected objects between Flat Lines and Wireframe. Create working plane proxy: creates a working plane proxy to save the current Draft working plane.

Additional tools

The Draft → Utilities menu contains several tools. Most of them can also be accessed from toolbars or the Draft Tray and have already been mentioned above. For the following tools this is not the case: Apply current style: applies the current style settings to selected objects. Heal: heals problematic Draft objects found in very old files. Toggle continue mode: switches continue mode on or off. Show snap toolbar: shows the Draft Snap toolbar.

Additional features

Working plane: the plane in the 3D view where new Draft objects are created. Snapping: select exact geometric points on, or defined by, existing objects or the grid. Constraining: for each subsequent point you can constrain the movement of the cursor to the X, Y, or Z direction. Construction mode: places new Draft objects in a dedicated group making it easier to hide or delete them. Pattern: Draft objects with a DataMake Face property can display an SVG pattern instead of a solid face color.

Tree view context menu

The following additional options are available in the Tree view context menu:

Default options

If there is an active document the context menu contains one additional sub-menu: Utilities: a subset of the tools available in the main Draft Utilities menu.

Wire options

For a Draft Wire, Draft BSpline, Draft CubicBezCurve and Draft BezCurve this additional option is available: Flatten this wire: flattens the wire based on its internal geometry. This option currently does not work properly.

Layer container options

For a Draft LayerContainer these additional options are available: Merge layer duplicates: merges all layers with the same base label. This does not work in FreeCAD version 0.19. Add new layer: adds a new layer to the current document.

Layer options

For a Draft Layer these additional options are available: Activate this layer: activates the selected layer. Select layer contents: selects the objects inside the selected layer.

Working plane proxy options

For a Draft WorkingPlaneProxy these additional options are available: Write camera position: updates the ViewView Data property of the working plane proxy with the current 3D view camera settings. Write objects state: updates the ViewVisibility Map property of the working plane proxy with the current visibility state of objects in the document.

3D view context menu

The following additional options are available in the 3D view context menu:

Default options

If there is an active document the context menu contains one additional sub-menu: Utilities: a subset of the tools available in the main Draft Utilities menu.

Obsolete tools

These commands are obsolete but still available: Array: creates an orthogonal array from a selected object. The created array can be turned into a polar array or a circular array by changing its DataArray Type property. obsolete in version 0.19 Drawing: inserts views of selected objects into a drawing page. obsolete in version 0.17

Preferences

Preferences: general preferences for the Draft Workbench. Import Export Preferences: preferences available for importing from and exporting to different file formats.

File formats

The Draft Workbench provides FreeCAD with importers and exporters for several file formats. These are used by the Std Import and Std Export commands. Autodesk .DXF: imports and exports Drawing Exchange Format files. See also FreeCAD and DXF Import. Autodesk .DWG: imports and exports DWG files via an external DWG converter. See also FreeCAD and DWG Import. Scalable Vector Graphics .SVG: imports and exports Scalable Vector Graphics files. Open Cad format .OCA: imports and exports OCA/GCAD files. Airfoil Data Format .DAT: imports DAT files describing Airfoil profiles.

Unit tests

See also: Test Workbench. To run the unit tests of the workbench execute the following from the operating system terminal: freecad -t TestDraft

Scripting

See also: Autogenerated API documentation and FreeCAD Scripting Basics. The workbench includes a module to create samples of all objects in a new document. introduced in version 0.19 Use this to test that all objects are produced correctly: import drafttests.draft_test_objects as dto doc = dto.create_test_file() Inspecting the code of this module can help to understand the programming interface.

Tutorials

Draft tutorial Draft ShapeString tutorial


FEM Workbench

Introduction

The FEM Workbench provides a modern finite element analysis (FEA) workflow for FreeCAD. Mainly this means all tools to make an analysis are combined into one graphical user interface (GUI).

Workflow

The steps to carry out a finite element analysis are:
    Preprocessing: setting up the analysis problem.
      Modeling the geometry: creating the geometry with FreeCAD, or importing it from a different application. Creating an analysis.
        Adding simulation constraints such as loads and fixed supports to the geometric model. Adding materials to the parts off the geometric model. Creating a finite element mesh for the geometrical model, or importing it from a different application.
    Solving: running an external solver from within FreeCAD. Postprocessing: visualizing the analysis results from within FreeCAD, or exporting the results so they can be postprocessed with another application.
The FEM Workbench can be used on Linux, Windows, and Mac OSX. Since the workbench makes use of external solvers, the amount of manual setup will depend on the operating system that you are using. See FEM Install for instructions on setting up the external tools. Workflow of the FEM Workbench; the workbench calls two external programs to perform meshing of a solid object, and perform the actual solution of the finite element problem

Menu: Model

Analysis container: Creates a new container for a mechanical analysis. If a solid is selected in the tree view before clicking on it, the meshing dialog will be opened next.

Materials

Material for solid: Lets you select a solid material from the database. Material for fluid: Lets you select a fluid material from the database. Nonlinear mechanical material: Lets you add a nonlinear mechanical material model. Reinforced material (concrete): Lets you select reinforced materials consisting of a matrix and a reinforcement from the database. Material editor: Lets you open the material editor to edit materials.

Element Geometry

Beam cross section: Used to define cross sections for beam elements. Beam rotation: Used to rotate cross sections of beam elements. Shell plate thickness: Used to define shell element thickness. Fluid section for 1D flow: Creates a FEM fluid section element for pneumatic and hydraulic networks.

Electrostatic Constraints

Constraint electrostatic potential:

Fluid Constraints

Constraint initial flow velocity: Used to define an initial flow velocity for the domain. Constraint flow velocity: Used to define a flow velocity as a boundary condition at an edge (2D) or face (3D).

Geometrical Constraints

Constraint plane rotation: Used to define a plane rotation constraint on a planar face. Constraint section print: introduced in version 0.19 Constraint transform: Used to define a transform constraint on a face.

Mechanical Constraints

Constraint fixed: Used to define a fixed constraint on point/edge/face(s). Constraint displacement: Used to define a displacement constraint on point/edge/face(s). Constraint contact: Used to define a contact constraint between two faces. Constraint tie: Used to define a tie constraint ("bonded contact") between two faces. introduced in version 0.19 Constraint spring: Used to define a spring. introduced in version 0.20 Constraint force: Used to define a force in [N] applied uniformly to a selectable face in a definable direction. Constraint pressure: Used to define a pressure constraint. Constraint self weight: Used to define a gravity acceleration acting on a model.

Thermal Constraints

Constraint initial temperature: Used to define the initial temperature of a body. Constraint heatflux: Used to define a heat flux constraint on a face(s). Constraint temperature: Used to define a temperature constraint on a point/edge/face(s). Constraint body heat source: Used to define an internally generated body heat.

Constraints without solver

Fluid boundary condition: Constraint bearing: Used to define a bearing constraint. Constraint gear: Used to define a gear constraint. Constraint pulley: Used to define a pulley constraint.

Overwrite Constants

Constant vacuum permittivity: introduced in version 0.19

Menu: Mesh

FEM mesh from shape by Netgen: FEM mesh from shape by Gmsh: FEM mesh boundary layer: Creates anisotropic meshes for accurate calculations near boundaries. FEM mesh region: Creates a localized area(s) to mesh which highly optimizes analysis time. FEM mesh group: Groups and labels elements of a mesh (vertex, edge, surface) together, useful for exporting the mesh to external solvers. Nodes set: Creates/defines a node set from FEM mesh. FEM mesh to mesh: Convert the surface of a FEM mesh to a mesh.

Menu: Solve

Solver CalculiX Standard: Creates a new solver for this analysis. In most cases the solver is created together with the analysis. Solver CalculiX (experimental): Solver Elmer: Creates the solver controller for Elmer. It is independent from other solver objects. Solver Mystran: Solver Z88: Elasticity equation: Electricforce equation: introduced in version 0.19 Electrostatic equation: Flow equation: Flux equation: Heat equation: Solver job control: Opens the menu to adjust and start the selected solver. Run solver calculations: Runs the selected solver of the active analysis.

Menu: Results

Purge results: Deletes the results of the active analysis. Show result: Used to display the result of an analysis. Apply changes to pipeline: Post pipeline from result: Warp filter: Scalar clip filter: Function cut filter: Region clip filter: Line clip filter: Stress linearization plot: Data at point clip filter: Filter functions:

Menu: Utilities

Clipping plane on face: Remove all clipping planes: Open FEM examples: Open the GUI to access FEM examples.

Context Menu

Clear FEM mesh: Deletes the mesh file from the FreeCAD file. Useful to make a FreeCAD file lighter. Display FEM mesh info: Displays basic statistics of existing mesh - number of nodes and elements of each type.

Preferences

Preferences...: Preferences available in FEM Tools.

Information

The following pages explain different topics of the FEM Workbench. FEM Install: a detailed description on how to set up the external programs used in the workbench. FEM Mesh: further information on obtaining a mesh for finite element analysis. FEM Solver: further information on the different solvers available in the workbench, and those that could be used in the future. FEM CalculiX: further information on CalculiX, the default solver used in the workbench for structural analysis. FEM Concrete: interesting information on the topic of simulating concrete structures. FEM Project: further information on the unit system, limitations, and the development ideas and roadmap of the workbench.

Tutorials

Tutorial 1: FEM CalculiX Cantilever 3D; basic simply supported beam analysis. Tutorial 2: FEM Tutorial; simple tension analysis of a structure. Tutorial 3: FEM Tutorial Python; set up the cantilever example entirely through scripting in Python, including the mesh. Tutorial 4: FEM Shear of a Composite Block; see the deformation of a block that is comprised of two materials. Tutorial 5: Transient FEM analysis Tutorial 6: Post-Processing_of_FEM_Results_with_Paraview Tutorial 7: FEM Example Capacitance Two Balls; Elmer's GUI tutorial 6 "Electrostatics Capacitance Two Balls" using FEM Examples.
Coupled thermal mechanical analysis tutorials by openSIM Video tutorial 1: FEM video for beginner (including YouTube link) Video tutorial 2: FEM video for beginner (including YouTube link) Many video tutorials: anisim Open Source Engineering Software (in German)

Extending the FEM Workbench

The FEM Workbench is under constant development. An objective of the project is to find ways to easily interact with various FEM solvers, so that the end user can streamline the process of creating, meshing, simulating, and optimizing an engineering design problem, all within FreeCAD. The following information is aimed at power users and developers who want to extend the FEM Workbench in different ways. Familiarity with C++ and Python is expected, and also some knowledge of the "document object" system used in FreeCAD is necessary; this information is available in the Power users hub and the Developer hub. Please notice that since FreeCAD is under active development, some articles may be too old, and thus obsolete. The most up to date information is discussed in the FreeCAD forums, in the Development section. For FEM discussions, advice or assistance in extending the workbench, the reader should refer to the FEM subforum. The following articles explain how the workbench can be extended, for example, by adding new types of boundary conditions (constraints), or equations. Extend FEM Module Onboarding FEM Devs attempts to orient new devs on how to contribute to the FEM workbench. Add FEM Constraint Tutorial Add FEM Equation Tutorial A developer's guide has been written to help power users in understanding the complex FreeCAD codebase and the interactions between the core elements and the individual workbenches. The book is hosted at github so multiple users can contribute to it and keep it updated. Early preview of ebook: Module developer' guide to FreeCAD source forum thread. FreeCAD Mod Dev Guide github repository.

Extending the FEM Workbench documentation

More information regarding extending or missing FEM documentation can be found in the forum: FEM documentation missing on the Wiki


Mesh Workbench

Introduction

The Mesh Workbench handles triangle meshes. Meshes are a special type of 3D object, composed of triangular faces connected by their vertices and edges. Many 3D applications, like Sketchup, Blender, Maya and 3D Studio Max, use meshes as their primary type of 3D object. Since meshes are very simple objects, containing only vertices (points), edges and triangular faces, they are very easy to create, modify, subdivide, stretch, and can easily be passed from one application to another without any loss of details. In addition, since meshes contain very simple data, 3D applications can usually manage very large quantities of them without using a lot of resources. For these reasons, meshes are often the 3D object type of choice for applications dealing with movies, animation, and image creation. However, in the field of engineering meshes present a big limitation: they cannot accurately define curved surfaces. This is why FreeCAD relies on PartDesign Workbench.

Tools

All Mesh Workbench tools can be accessed from the Meshes menu. Almost all are also available in one of the Mesh toolbars. Import mesh...: Imports a mesh object from a file. Export mesh...: Exports a mesh object to a file. Create mesh from shape...: Creates mesh objects from shape objects. Refinement...: Remeshes a mesh object. introduced in version 0.19 Analyze Evaluate and repair mesh...: Evaluates and repairs a mesh object. Face info: Shows information about faces of mesh objects. Curvature info: Shows the absolute curvature of curvature objects at selected points. Check solid mesh: Checks if a mesh object is solid. Boundings info...: Shows the bounding box coordinates of a mesh object. Curvature plot: Creates Mesh Curvature objects for mesh objects. Harmonize normals: Harmonizes the normals of mesh objects. Flip normals: Flips the normals of mesh objects. Fill holes...: Fills holes in mesh objects. Close hole: Fills selected holes in mesh objects. Add triangle: Adds faces along a boundary of an open mesh object. Remove components...: Removes faces from mesh objects. Remove components by hand...: Removes components from mesh objects. Create mesh segments...: Creates separate mesh segments for specified surface types of a mesh object. Create mesh segments from best-fit surfaces...: Creates separate mesh segments for specified surface types of a mesh object, and can identify their parameters. Smooth...: Smooths mesh objects. Decimation...: Reduces the number of faces in mesh objects. introduced in version 0.19 Scale...: Scales mesh objects. Regular solid...: Creates a regular parametric solid mesh object. Boolean Union: Creates a mesh object that is the union of two mesh objects. Intersection: Creates a mesh object that is the intersection of two mesh objects. Difference: Creates a mesh object that is the difference of two mesh objects. Cutting Cut mesh: Cuts whole faces from mesh objects. Trim mesh: Trims faces and parts of faces from mesh objects. Trim mesh with a plane: Trims faces and parts of faces on one side of a plane from a mesh object. Create section from mesh and plane: Creates a cross section across a mesh object. Cross-sections...: Creates multiple cross sections across mesh objects. introduced in version 0.19 Merge: Creates a mesh object by combining the meshes of two or more mesh objects. Split by components: Splits a mesh object into its components. introduced in version 0.19 Unwrap Mesh: Creates a flat representation of a mesh object. introduced in version 0.19 Unwrap Face: Creates a flat representation of a face of a shape object. introduced in version 0.19

Preferences

There are some export preferences related to Mesh Formats but these are not used by commands belonging to this workbench. They are used by the Std Export command. Mesh Workbench preferences can be found in the following categories of the Preferences Editor: Display: On the Mesh view tab several preferences can be set. OpenSCAD: The Mesh Union, Mesh Intersection and Mesh Difference commands require OpenSCAD and use the OpenSCAD executable preference to find its executable.

Notes

More mesh tools are available in the OpenSCAD Workbench. See Mesh Scripting to manipulate and create meshes using Python. See also FreeCAD and Mesh Import See Asymptote to export meshes to the Asymptote format.


OpenSCAD Workbench

Dependencies

In FreeCAD 0.19, the Ply (Python-Lex-Yacc) module, which is used to import CSG files, was removed from the FreeCAD source code, as it is a third party library not developed by FreeCAD. As a result, you now need to install Ply before using the OpenSCAD Workbench. When using a pre-packaged, stable version of FreeCAD this dependency should be installed automatically in all platforms; in other cases, for example, when compiling from source, you may have to install it from an online repository. In openSUSE this is done by: sudo zypper install python3-ply In Debian/Ubuntu based systems this is done like the following: sudo apt install python3-ply The general installation in all platforms can be done from the Python package index. pip3 install --user ply

OpenSCAD language and file format

The OpenSCAD language allows the use of variables and loops. It allows you to specify sub-modules to reuse geometry and code. This high degree of flexibility makes parsing very complex. Currently the OpenSCAD Workbench cannot handle the OpenSCAD language natively. Instead, if OpenSCAD is installed, it can be used to convert the input to the CSG format, which is a subset of the OpenSCAD language, and can be used as the input to OpenSCAD for further processing. During conversion all parametric behavior is lost, meaning that all variable names are discarded, loops expanded, and mathematical expressions evaluated.

Tools

Color Code Shape: Change the color of selected or all shapes based on their validity. Replace Object: Replace an object in the feature tree. Remove Subtree: Removes the selected objects and all children that are not referenced from other objects. Refine Shape Feature: Create Refine Shape Feature. Mirror Mesh Feature: Create Mirror Mesh Feature. Scale Mesh Feature: Scale a Mesh Feature. Resize Mesh Feature: Resize a Mesh Feature. Increase Tolerance Feature: Increases tolerance of edges/faces/vertex of selected object(s). Convert Edges To Faces: Convert edges to faces. Useful to prepare imported DXF geometry for extrusion. Expand Placements: Expand all placements downwards the FeatureTree. Explode Group: Explodes fused part primitives. Add OpenSCAD Element: Add an OpenSCAD element by entering OpenSCAD code into the task panel. Mesh Boolean: Creates new mesh object by boolean operation from shapes. Hull: Applies a hull to selected shapes. Minkowski: Applies a minkowski sum to selected shapes.

Preferences

Preferences: preferences available for the OpenSCAD tools.

Limitations

OpenSCAD creates constructive solid geometry, as well as imports mesh files and extrudes 2D geometry from DXF files. FreeCAD allows you to create CSG with primitives as well. The FreeCAD geometry kernel (OCCT) works using a boundary representation. Therefore conversion from CSG to BREP should, in theory, be possible whereas conversion from BREP to CSG is, in general, not. OpenSCAD works internally on meshes. Some operations which are useful on meshes are not meaningful on a BREP model and can not be fully supported. Among these are convex hull, minkowski sum, glide and subdiv. Currently we run the OpenSCAD binary in order to perform hull and minkwoski operations and import the result. This means that the involved geometry will be triangulated. In OpenSCAD non-uniform scaling is often used, which does not impose any problems when using meshes. In our geometry kernel geometric primitives (lines, circular sections, etc) are converted to BSpline prior to performing such deformations. Those BSplines are known to cause trouble in later boolean operations. An automatic solution is not available at the moment. Please feel free to post to the forum if you encounter such problems. Often such problems can be solved be remodeling small parts. A deformation of a cylinder can substituted by an extrusion of an ellipses.

Hints

When importing DXF set the Draft precision to a sensible amount as this will affect the detection of connected edges. If FreeCAD crashes when importing CSG, it is strongly recommended that you enable "automatically check model after boolean operation" in Menu → Edit → Preferences → Part Design → Model setting.

Tutorials

Import OpenSCAD code

Links

OpenSCAD source code repository on GitHub Open tickets tagged "Openscad" on the FreeCAD bugtracker Things tagged with "OpenSCAD" on Thingiverse


Part Module

Introduction

The solid modelling capabilities of FreeCAD are based on the PartDesign, etc.), are based on these functions exposed by the Part Workbench. Therefore, the Part Workbench is considered the core component of the modelling capabilities of FreeCAD. A more detailed discussion of Part workbench versus Part Design workbench can be found here: Part and Part Design. The objects created with the Part Workbench are relatively simple; they are intended to be used with boolean operations (unions and cuts) in order to build more complex shapes. This modeling paradigm is known as the constructive solid geometry (CSG) workflow, and it was the traditional methodology used in early CAD systems. On the other hand, the PartDesign Workbench provides a more modern workflow to constructing shapes: it uses a parametrically defined sketch, that is extruded to form a basic solid body, which is then modified by parametric transformations (feature editing), until the final object is obtained. Part objects are more complex than mesh objects created with the Mesh Workbench, as they permit more advanced operations like coherent boolean operations, modifications history, and parametric behaviour. The Part Workbench is the basic layer that exposes the OCCT drawing functions to all workbenches in FreeCAD.

Tools

The tools are located in the Part menu or the Measure menu.

Primitives

These are tools for creating primitive objects. Box: Creates a box. Cylinder: Creates a cylinder. Sphere: Creates a sphere. Cone: Creates a cone. Torus: Creates a torus (ring). Tube: Creates a tube. introduced in version 0.19 Primitives: A tool to create one of the following primitives: Plane: Creates a plane. Box tool. Cylinder tool. Cone tool. Sphere tool. Ellipsoid: Creates a ellipsoid. Torus tool. Prism: Creates a prism. Wedge: Creates a wedge. Helix: Creates a helix. Spiral: Creates a spiral. Circle: Creates a circular edge. Ellipse: Creates an elliptical edge. Point: Creates a point (vertex). Line: Creates a line (edge). Regular Polygon: Creates a regular polygon. Builder: Creates shapes from various primitives.

Creation and modification

These are tools for creating new and modifying existing objects. Extrude: Extrudes planar faces. Revolve: Creates a solid by revolving an object (not a solid) around an axis. Mirror: Mirrors the selected object across a mirror plane. Fillet: Fillets (rounds) edges of an object. Chamfer: Chamfers edges of an object. Make face from wires: Makes a face from a set of wires (contours). introduced in version 0.19 Ruled Surface: Creates a ruled surface. Loft: Lofts from one profile to another. Sweep: Sweeps one or more profiles along a path. Section: Creates a section by intersecting an object with a section plane. Cross sections...: Creates one or more cross-sections through an object. Offset tools: 3D Offset: Constructs a parallel shape at a certain distance from an original. 2D Offset: Constructs a parallel wire at certain distance from an original, or enlarges/shrinks a planar face. Thickness: Hollows out a solid. Projection on surface: Projects a logo, text or any face, wire or edge onto a surface. introduced in version 0.19 Attachment: Attaches an object to another object.

Boolean

These tools perform boolean operations. Compound Tools: Make compound: Creates a compound from the selected objects. Explode Compound: Splits up compounds. Compound Filter: Extracts the individual pieces from compounds. Boolean: Performs boolean operations on objects. Cut: Cuts (subtracts) one object from another. Fuse: Fuses (unions) two objects. Common: Extracts the common (intersection) part of two objects. Join features: Connect: Connects interiors of walled objects. Embed: Embeds a walled object into another walled object. Cutout: Creates a cutout in a wall of an object for another walled object. Splitting tools: Boolean fragments: Creates all pieces obtained from Boolean operations. Slice a part: Slices and splits an object by intersecting it with other objects. Slice: Slices an object by intersecting it with other objects. XOR: Removes space shared by an even number of objects (symmetric version of Cut).

Measure

Measure: Tools for linear and angular measurements. Measure Linear: Creates a linear measurement. Measure Angular: Creates an angular measurement. Measure Refresh: Updates all measurements. Clear All: Clears all measurements. Toggle All: Shows or hides all measurements. Toggle 3D: Shows or hides 3D measurements. Toggle Delta: Shows or hides delta measurements.

Other tools

Import: Imports from *.IGES, *.STEP, or *.BREP files. Export: Exports to *.IGES, *.STEP, or *.BREP files. BoxSelection: Selects faces from a rectangular area. Shape from Mesh: Creates a shape object from a mesh object. Points from mesh: Creates a shape object made of points from a mesh object. introduced in version 0.19 Convert to solid: Converts a shape object to a solid object. Reverse shapes: Flips the normals of all faces of selected objects. Create a copy: Create simple copy: Creates a simple copy of a selected object. Create transformed copy: Creates a transformed copy of a selected object. introduced in version 0.19 Create shape element copy: Creates a copy from an element (vertex, edge, face) of a selected object. introduced in version 0.19 Refine shape: Cleans faces by removing unnecessary lines. Check geometry: Checks the geometry of selected objects for errors. Defeaturing: Removes features from an object.

Context menu items

Appearance: Determines the appearance of a whole object (color, transparency etc.). Set colors: Assigns colors to individual faces of objects.

Preferences

Preferences: Preferences available for Part Tools (the Part workbench also uses the PartDesign Preferences). Import Export Preferences: Preferences available for importing from and exporting to different file formats. Fine-tuning: Some extra parameters to fine-tune Part behavior.

Scripting

See Part scripting.

Tutorials

Import from STL or OBJ : How to import STL/OBJ files in FreeCAD Export to STL or OBJ : How to export STL/OBJ files from FreeCAD Whiffle Ball tutorial : How to use the Part Module


PartDesign Workbench

Introduction

The PartDesign Workbench provides advanced tools for modeling complex solid parts. It is mostly focused on creating mechanical parts that can be manufactured and assembled into a finished product. Nevertheless, the created solids can be used in general for any other purpose such as architectural design, finite element analysis, or machining and 3D printing. The PartDesign Workbench is intrinsically related to the Sketcher Workbench. The user normally creates a Sketch, then uses the PartDesign Pad tool to extrude it and create a basic solid, and then this solid is further modified. While the Part Workbench is based on a constructive solid geometry (CSG) methodology for building shapes, the PartDesign Workbench uses a parametric, feature editing methodology, which means a basic solid is sequentially transformed by adding features on top until the final shape is obtained. See the feature editing page for a more complete explanation of this process, and then see Creating a simple part with PartDesign to get started with creating solids. A more detailed discussion of Part workbench versus Part Design workbench can be found here: Part and Part Design. The bodies created with PartDesign are often subject to the topological naming problem which causes internal features to be renamed when the parametric operations are modified. This problem can be minimized by following the best practices described in the feature editing page, and by taking advantage of datum objects as support for sketches and features.

Tools

The Part Design tools are all located in the Part Design menu and the PartDesign toolbar that appear when you load the Part Design workbench.

Structure tools

These tools are in fact not part of the PartDesign Workbench. They belong to the Std Base system. They were developed in v0.17 with the intention that they would be useful to organize a model, and create assemblies; as such, they are very useful when working with bodies created with this workbench. Part: adds a new Part container in the active document and makes it active. Group: adds a Group container in the active document, which allows organizing the objects in the tree view.

Part Design Helper tools

Create body: creates a Body object in the active document and makes it active. Create sketch: creates‎ a new sketch on a selected face or plane. If no face is selected while this tool is executed, the user is prompted to select a plane from the Tasks panel. The interface then switches to the Sketcher Workbench in sketch editing mode. Edit sketch: Edit the selected Sketch. Map sketch to face: Maps a sketch to a previously selected plane or a face of the active body.

Part Design Modeling tools

Datum tools

Create a datum point: creates a datum point in the active body. Create a datum line: creates a datum line in the active body. Create a datum plane: creates a datum plane in the active body. Create a local coordinate system: creates a local coordinate system attached to datum geometry in the active body. Create a shape binder: creates a shape binder in the active body. Create a sub-object shape binder: creates a shape binder to a subelement, like edge or face from another body, while retaining the relative position of that element. introduced in version 0.19 Create a clone: creates a clone of the selected body.

Additive tools

These are tools for creating base features or adding material to an existing solid body. Pad: extrudes a solid from a selected sketch. Revolution: creates a solid by revolving a sketch around an axis. The sketch must form a closed profile. Additive loft: creates a solid by making a transition between two or more sketches. Additive pipe: creates a solid by sweeping one or more sketches along an open or closed path. Additive helix: creates a solid by sweeping a sketch along a helix. introduced in version 0.19 Create an additive primitive: adds an additive primitive to the active body. Additive box: creates an additive box. Additive cone: creates an additive cone. Additive cylinder: creates an additive cylinder. Additive ellipsoid: creates an additive ellipsoid. Additive prism: creates an additive prism. Additive sphere: creates an additive sphere. Additive torus: creates an additive torus. Additive wedge: creates an additive wedge.

Subtractive tools

These are tools for subtracting material from an existing body. Pocket: creates a pocket from a selected sketch. Hole: creates a hole feature from a selected sketch. The sketch must contain one or multiple circles. Groove: creates a groove by revolving a sketch around an axis. Subtractive loft: creates a solid shape by making a transition between two or more sketches and subtracts it from the active body. Subtractive pipe: creates a solid shape by sweeping one or more sketches along an open or closed path and subtracts it from the active body. Subtractive helix: creates a solid shape by sweeping a sketch along a helix and subtracts it from the active body. introduced in version 0.19 Create a subtractive primitive: adds a subtractive primitive to the active body. Subtractive box: adds a subtractive box to the active body. Subtractive cone: adds a subtractive cone to the active body. Subtractive cylinder: adds a subtractive cylinder to the active body. Subtractive ellipsoid: adds a subtractive ellipsoid to the active body. Subtractive prism: adds a subtractive prism to the active body. Subtractive sphere: adds a subtractive sphere to the active body. Subtractive torus: adds a subtractive torus to the active body. Subtractive wedge: adds a subtractive wedge to the active body.

Transformation tools

These are tools for transforming existing features. They will allow you to choose which features to transform. Mirrored: mirrors one or more features on a plane or face. Linear Pattern: creates a linear pattern based on one or more features. Polar Pattern: creates a polar pattern of one or more features. Create MultiTransform: creates a pattern with any combination of the other transformations.

Dress-up tools

These tools apply a treatment to the selected edges or faces. Fillet: fillets (rounds) edges of the active body. Chamfer: chamfers edges of the active body. Draft: applies an angular draft to selected faces of the active body. Thickness: creates a thick shell from the active body and opens selected face(s).

Boolean

Boolean operation: imports one or more Bodies or PartDesign Clones into the active body and applies a Boolean operation.

Extras

Some additional functionality found in the Part Design menu: Migrate: migrates files created with older FreeCAD versions. If the file is pure PartDesign feature-based, migration should succeed. If the file contains mixed Part/Part Design/Draft objects, the conversion will most likely fail. Sprocket design wizard: creates a sprocket profile that can be padded. introduced in version 0.19 Involute gear design wizard: creates an involute gear profile that can be padded. Shaft design wizard: Generates a shaft from a table of values and allows to analyze forces and moments. The shaft is made with a revolved sketch that can be edited.

Context Menu items

Set tip: redefines the tip, which is the feature exposed outside of the Body. Move object to other body: moves the selected sketch, datum geometry or feature to another Body. Move object after other object: allows reordering of the Body tree by moving the selected sketch, datum geometry or feature to another position in the list of features.

Items shared with the Part workbench

Appearance: determines appearance of the whole part (color transparency etc.). Set colors: assigns colors to part faces.

Preferences

Preferences: preferences available for PartDesign Tools. Fine tuning: some extra parameters to fine-tune PartDesign behavior.

Tutorials

How to use FreeCAD, a website describing the workflow for mechanical design. Creating a simple part with PartDesign Basic Part Design Tutorial PartDesign Bearingholder Tutorial I (needs updating) PartDesign Bearingholder Tutorial II (needs updating)


Path Workbench

Introduction

The Path Workbench is used to produce machine instructions for CNC machines from a FreeCAD 3D model. These produce real-world 3D objects on CNC machines such as mills, lathes, lasercutters, or similar. Typically, instructions are a G-code dialect. A general CNC lathe tool path sequence simulation example is presented here. The FreeCAD Path Workbench workflow creates these machine instructions as follows: A 3D model is the base object, typically created using one or more of the Draft Workbenches. A Path Job is created in the Path Workbench. This contains all the information required to generate the necessary G-code to process the Job on a CNC mill: there is Stock material, the mill has a certain set of tools and it follows certain commands controlling speed and movements (usually G-code). Path Tools are selected as required by the Job Operations. Milling paths are created using e.g. Contour and Pocket Operations. These Path objects use internal FreeCAD G-code dialect, independent of the CNC machine. Export the job with a G-code, matching to your machine. This step is called post processing; there are different post processors available.

General concepts

The Path Workbench generates G-code defining the paths required to mill the Project represented by the 3D model on the target mill in the Path Job Operations FreeCAD G-code dialect, which is later translated to the appropriate dialect for the target CNC controller by selecting the appropriate postprocessor. The G-code is generated from directives and Operations contained in a Path Job. The Job Workflow lists these in the order they will be executed. The list is populated by adding Path Operations, Path Dressups, Path Supplemental Commands, and Path Modifications from the Path Menu, or GUI buttons. The Path Workbench provides a Tool Manager (Library, Tool-Table), and G-code Inspection, and Simulation tools. It links the Postprocessor, and allows importing and exporting Job Templates. The Path Workbench has external dependencies including:
    The FreeCAD 3D model units are defined in the Edit → Preference → General → Units tab's Units settings. The Postprocessor configuration defines the final G-code units. The Macro file path, and Geometric tolerances, are defined in the Edit → Preferences → Path → Job Preferences tab. Colors are defined in the Edit → Preferences → Path → Path colors tab. Holding tag parameters are defined in the Edit → Preferences → Path → Dressups tab. That the Base 3D model quality supports the Path workbench requirements, passes Check Geometry.

Limitations

Some current limitations of which you should be aware are: Most of the Path Tools are not true 3D tools but only 2.5D capable. This means that they take a fixed 2D shape and can cut it down to a given depth. However, there are two tools which produce true 3D paths: 3D Surface (which is still an experimental feature as of November 2020). Most of Path workbench is designed for a simple, standard 3-axis (xyz) CNC mill/router, but lathe tools are under development in 0.19_pre. Most operations in Path workbench will return paths based on a standard endmill tool/bit only, regardless of the tool/bit type assigned in a given tool controller with the exception of the 3D Surface operations. The operations within the Path workbench are not aware of clamping mechanisms in use to secure the model to your machine. Consequently, please review and simulate the paths you generate prior to sending the code to your machine. If necessary, model your clamping mechanisms in FreeCAD in order to better inspect the paths generated. Look for possible collisions with clamps or other obstacles along the paths.

Units

Unit handling in Path can be confusing. There are several points to understand:
    FreeCAD base units for length and time are 'mm' and 's' respectively. Velocity is thus 'mm/s'. This is what FreeCAD stores internally regardless of anything else The default unit schema uses the default units. If you're using the default schema and you enter a feed rate without a unit string, it will get entered as 'mm/s' Most CNC machines expect feed rate in the form of either 'mm/min' or 'in/min'. Most post-processors will automatically convert the unit when generating gcode.
Schemas:
    Changing schema in preferences changes default unit string for the input fields. If you're a Path user and prefer to design in metric, it's highly recommended that you use the "Metric Small Parts & CNC" schema. If you design in US units, either the Imperial Decimal and Building US will work Changing your preferred unit schema will have no effect on output but will help avoid input errors
Output:
    Generating the correct unit in output is the responsibility of the post-processor and is done only at that time Machine output unit is completely unrelated to your selected unit schema Post-processors produce either metric (G21) output, Imperial (G20) output or are configurable. Configurable post-processors default to metric (G21) If you want your configurable post-processor to output imperial gcode (G20), Set the correct argument in your job output configation (ie --inches for linuxcnc). This can be stored in a job template and set as your default template to make it automatic for all future jobs
Path Inspection:
    If you use the Path Inspect tool to look at g-code, you will see it in 'mm/s' because it is not being post-processed

Heights and depths

Many of the commands have various heights and depths: Visual reference for Depth properties (settings)

Commands

Some commands are experimental and not available by default. To enable them see Path experimental.

Project Commands

Job: Creates a new CNC job. Post Process: Exports a project to G-code. Check the path job for common errors: Checks the selected job for missing values. Experimental. introduced in version 0.19 Export Template: Export the current job as a template.

Tool Commands

Inspect G-code: Shows the G-code for checking. CAM Simulator: Shows the milling operation like it's done on the machine. Finish Selecting Loop: Completes a loop from two selected edges. Toggle the Active State of the Operation: Activates or de-activates a path operation. ToolBit Library editor: Opens an editor to manage ToolBit libraries. introduced in version 0.19 ToolBit Dock: Toggles the ToolBit Dock. introduced in version 0.19

Basic Operations

Profile: Creates a profile operation of the entire model, or from one or more selected faces or edges. introduced in version 0.19 Pocket Shape: Creates a pocketing operation from one ore more selected pocket(s). Drilling: Performs a drilling cycle. Face: Creates a surfacing path. Helix: Creates a helical path. Adaptive: Creates an adaptive clearing and profiling operation. Slot: Creates a slotting operation from selected features or custom points. Experimental. introduced in version 0.19 Engrave: Creates an engraving path. Vcarve: Creates an engraving path using a V tool shape. introduced in version 0.19

3D Operations

3D Pocket: Creates a path for a 3D pocket. 3D Surface: Creates a path for a 3D surface. Experimental. introduced in version 0.19 Waterline: Creates a waterline path for a 3D surface. Experimental. introduced in version 0.19

Path Dressup

Boundary Dressup: Adds a boundary dressup modification to a selected path. Dogbone Dressup: Adds a dogbone dressup modification to a selected path. DragKnife Dressup: Adds a dragknife dressup modification to a selected path. LeadInOut Dressup: Adds a lead-in and/or lead-out point to a selected path. RampEntry Dressup: Adds ramp entry dressup modification to a selected path. Tag Dressup: Adds a holding tag dressup modification to a selected path.

Supplemental Commands

Fixture: Changes the fixture position. Comment: Inserts a comment in the G-code of a path. Stop: Inserts a full stop of the machine. Custom: Inserts custom G-code. From Shape: Creates a path object from a selected Part object. Experimental.

Path Modification

Copy the operation in the job: Creates a parametric Copy of a selected path object. Array: Creates an array by duplicating a selected path. Simple Copy: Creates a non-parametric copy of a selected path object.

Miscellaneous

Area: Creates a feature area from selected objects. Experimental. Area workplane: Creates a feature area workplane. Experimental.

Obsolete

Tool Manager: Edit the Tool Manager. 'Legacy' tool system. version 0.18 and below

ToolBit architecture

Manage tools, bits, and the Tool Library. Based on the ToolBit architecture. introduced in version 0.19 Path Tools Path ToolShape Path ToolBit Path ToolBit Library Path ToolController

Other

Path FAQ: The Path Workbench shares many concepts with other CAM software packages but has its own peculiarities. If something seems wrong this is a good place to start. Path SetupSheet: You can use a SetupSheet to customize how various property values for operations are calculated. Path Postprocessor Customization: If you have a special machine which cannot use one of the available post-processors you may need to write your own post-processor. Path fourth axis: Experimental four axis milling. Path Development Roadmap: Read this if you are a developer and want to contribute to Path.

Preferences

Preferences...: Preferences available for the Path Workbench.

Scripting

See Path scripting.

Tutorials

Path Walkthrough for the Impatient: a quick tutorial to get familiar with Path.

Videos

FreeCAD Path: Custom paths with Python - Part 1 - 5: a playlist with a series of 5 videos in English by sliptonic. This series shows how to work with the Path Workbench. FreeCAD CAM Path Workbench: a playlist with a series of 7 videos in English by CAD CAM Lessons. FreeCAD CAM CNC a playlist with a series of 8 videos in English by CAD CAM Lessons.


Points Workbench

The Points Workbench offers specific tools for working with point clouds. The workbench is still in development. A point cloud is a collection of points in 3D space. A point cloud is generally produced by scanning the surface of a solid object. The cloud of points can then be used for many purposes including building a mesh for the object, reconstructing the surfaces and solid volumes, reverse engineering, as well as for visualization and quality inspection.

Tools

All Points Workbench tools can be accessed from the Points menu. Some tools are also available in the Points tools toolbar. Convert to points...: Creates point clouds from shape objects. Structured point cloud: Creates a structured point cloud from the points of an existing point cloud. Import points...: Imports a point cloud from a file. Export points...: Exports a point cloud to a file. Cut point cloud: Cuts points from point clouds. Merge point clouds: Creates a point cloud by combining the points of two or more point clouds.

Notes

Draft Snap Endpoint to snap to the points. Python can be used to analyze and process point clouds. See the following forum discussions: Inspecting Point cloud. Fläche aus Messwerten (German) Schnitte durch Flächen aus Messwerten (German)


Raytracing Workbench

Nevertheless, the information in this page is generally useful for the new workbench, as both modules work basically in the same way. Raytracing workbench icon

Introduction

1 Introduction 2 Typical workflow 3 Tools 3.1 Project tools 3.2 Utilities 4 Preferences 5 Tutorials 6 Creating a povray file manually 7 Scripting 8 Links 8.1 POV-Ray 8.2 LuxRender 8.3 Future possible renderers to implement 9 Exporting to Kerkythea 10 Development The Raytracing Workbench is used to generate photorealistic images of your models by processing them with an external renderer. The Raytracing Workbench works with templates, which are project files that define a scene for your 3D model. You can place lights and geometry such as ground planes, and it also contains placeholders for the position of the camera, and for the material information of the objects in the scene. The project can then be exported to a ready-to-render file, or be rendered directly within FreeCAD. Currently, two renderers are supported: POV-Ray and LuxRender. To be able to render from within FreeCAD, at least one of these programs must be installed and configured in your system. However, if no renderer is installed, you will still be able to export a project file to be rendered at another time. The Raytracing workbench is essentially obsolete. New development is happening in the Render Workbench, which is intended as its replacement. This workbench is fully programmed in Python so it is much easier to extend than the current workbench which is programmed in C++. Nevertheless, the information in this page is generally useful for the new workbench, as both modules work basically in the same way.

Typical workflow

    Create or open a FreeCAD project, add some solid objects (Part-based or PartDesign-based); meshes are currently not supported. Create a Raytracing project (povray or luxrender). Select the objects that you wish to add to the Raytracing project and add them. Export the project file or render it directly.


Workflow of the Raytracing Workbench; the workbench prepares a project file from a given template, and then calls an external program to produce the actual rendering of the scene. The external renderer can be used independently of FreeCAD.

Tools

Project tools

These are the main tools for exporting your 3D work to external renderers. New PovRay project: Insert new PovRay project in the document New LuxRender project: Insert new LuxRender project in the document Insert part: Insert a view of a Part in a raytracing project Reset camera: Matches the camera position of a raytracing project to the current view Export project: Exports a raytracing project to a scene file for rendering in an external renderer Render: Renders a raytracing project with an external renderer

Utilities

These are helper tools to perform specific tasks manually. Export view to povray: Write the active 3D view with camera and all its content to a povray file Export camera to povray: Export the camera position of the active 3D view in POV-Ray format to a file Export part to povray: Write the selected Part (object) as a povray file

Preferences

Preferences: Preferences available in for the Raytracing tools.

Tutorials

Basic Raytracing tutorial Intermediate Raytracing tutorial

Creating a povray file manually

The utility tools described above allow you to export the current 3D view and all of its content to a Povray file. First, you must load or create your CAD data and position the 3D View orientation as you wish. Then choose "Utilities → Export View..." from the raytracing menu. You will be asked for a location to save the resulting *.pov file. After that you can open it in Povray and render: As usual in a renderer you can make big and nice pictures:

Scripting

See the Raytracing API example for information on writing scenes programmatically.

Links

POV-Ray

POV-Ray page on this wiki http://www.spiritone.com/~english/cyclopedia/ http://www.povray.org/ http://en.wikipedia.org/wiki/POV-Ray

LuxRender

LuxRender page on this wiki http://www.luxrender.net/

Future possible renderers to implement

http://www.yafaray.org/ http://www.mitsuba-renderer.org/ http://www.kerkythea.net/ http://www.artofillusion.org/

Exporting to Kerkythea

Although direct export to the Kerkythea XML-File-Format is not supported yet, you can export your Objects as Mesh-Files (.obj) and then import them in Kerkythea. if using Kerkythea for Linux, remember to install the WINE-Package (needed by Kerkythea for Linux to run) you can convert your models with the help of the mesh workbench to meshes and then export these meshes as .obj-files If your mesh-export resulted in errors (flip of normals, holes ...) you may try your luck with netfabb studio basic Free for personal use, available for Windows, Linux and Mac OSX. It has standard repair tools which will repair you model in most cases. another good program for mesh analysing/repairing is Meshlab Open Source, available for Windows, Linux and Mac OSX. It has standard repair tools which will repair you model in most cases (fill holes, re-orient normals, etc.) you can use "make compound" and then "make single copy" or you can fuse solids to group them before converting to meshes remember to set in Kerkythea an import-factor of 0.001 for obj-modeler, since Kerkythea expects the obj-file to be in m (but standard units-scheme in FreeCAD is mm) Within WIndows 7 64-bit Kerkythea does not seem to be able to save these settings. So remember to do that each time you start Kerkythea if importing multiple objects in Kerkythea you can use the "File → Merge" command in Kerkythea

Development

These pages refer to the new workbench, programmed in Python, meant to replace the current Raytracing Workbench. Render Workbench Render Workbench (announcement only, no discussion) FreeCAD Renderer Workbench improvements Outdated These pages refer to a replacement workbench, programmed in C++, proposed around 2012, which was never completed. Raytracing project Render project


Robot Workbench

The reason this workbench is still in the master source code is because this workbench is programmed in C++. If this workbench could be programmed in Python, then it could be made an external workbench and it could be moved to a separate repository.

Introduction

Robot workbench icon The Robot Workbench is a tool to simulate a standard 6-axis industrial robot, like Kuka. You can do the following tasks: Set up a simulation environment with a robot and work pieces. Create and fill up movement trajectories. Decompose features of a CAD part to a trajectory. Simulate the robot movement and reaching distance. Export the trajectory to a robot program file. To get started try the Robot tutorial, and see the programming interface in the RobotExample.py example file. 1 Introduction 2 Tools 2.1 Robots 2.2 Trajectories 2.2.1 Non parametric trajectories 2.2.2 Parametric trajectories 3 Scripting 4 Tutorials

Tools

Here the principal commands you can use to create a robot set-up.

Robots

The tools to create and manage the 6-Axis robots Create a robot: Insert a new robot into the scene Simulate a trajectory: Opens the simulation dialog and lets you simulate Export a trajectory: Export a robot program file Set home position: Set the home position of a robot Restore home position: move the robot to its home position

Trajectories

Tools to create and manipulate trajectories. There are two kinds, the parametric and non parametric ones.

Non parametric trajectories

Create a trajectory: Inserts a new empty trajectory-object into the scene Set the default orientation: Set the orientation way-points gets created by default Set the default speed parameter: Set the default values for way-point creation Insert a waypoint: Insert a way-point from the current robot position into a trajectory Insert a waypoint preselected: Insert a way-point from the current mouse position into a trajectory

Parametric trajectories

Create a trajectory out of edges: Insert a new object which decompose edges to a trajectory Dress-up a trajectory: Lets you override one or more properties of a trajectory Trajectory compound: Create a compound out of some single trajectories

Scripting

See the Robot API example for a description of the functions used to model the robot displacements.

Tutorials

Robot 6-Axis VRML Preparation for Robot Simulation


Sketcher Workbench

Introduction

The FreeCAD Sketcher Workbench is used to create 2D geometries intended for use in the PartDesign Workbench operations, the Sketcher also forms the basis of the feature editing methodology of creating solids. The Sketcher workbench features "constraints", allowing 2D shapes to follow precise geometrical definitions in terms of length, angles, and relationships (horizontality, verticality, perpendicularity, etc.). A constraint solver calculates the constrained-extent of 2D geometry and allows interactive exploration of degrees-of-freedom of the sketch. A fully constrained sketch

Basics of constraint sketching

To explain how the Sketcher works, it may be useful to compare it to the "traditional" way of drafting.

Traditional Drafting

The traditional way of CAD drafting inherits from the old drawing board. Orthogonal (2D) views are drawn manually and intended for producing technical drawings (also known as blueprints). Objects are drawn precisely to the intended size or dimension. If you want to draw an horizontal line 100mm in length starting at (0,0), you activate the line tool, either click on the screen or input the (0,0) coordinates for the first point, then make a second click or input the second point coordinates at (100,0). Or you will draw your line without regard to its position, and move it afterwards. When you've finished drawing your geometries, you add dimensions to them.

Constraint Sketching

The Sketcher moves away from this logic. Objects do not need to be drawn exactly as you intend to, because they will be defined later on by constraints. Objects can be drawn loosely, and as long as they are unconstrained, can be modified. They are in effect "floating" and can be moved, stretched, rotated, scaled, and so on. This gives great flexibility in the design process.

What are constraints?

Instead of dimensions, Constraints are used to limit the degrees of freedom of an object. For example, a line without constraints has 4 Degrees Of Freedom (abbreviated as "DOF"): it can be moved horizontally or vertically, it can be stretched, and it can be rotated. Applying a horizontal or vertical constraint, or an angle constraint (relative to another line or to one of the axes), will limit its capacity to rotate, thus leaving it with 3 degrees of freedom. Locking one of its points in relation to the origin will remove another 2 degrees of freedom. And applying a dimension constraint will remove the last degree of freedom. The line is then considered fully-constrained. Multiple objects can be constrained between one another. Two lines can be joined through one of their points with the coincident point constraint. An angle can be set between them, or they can be set perpendicular. A line can be tangent to an arc or a circle, and so on. A complex Sketch with multiple objects will have a number of different solutions, and making it fully-constrained means that just one of these possible solutions has been reached based on the applied constraints. There are two kinds of constraints: geometric and dimensional. They are detailed in the 'Tools' section below.

What the Sketcher is not good for

The Sketcher is not intended for producing 2D blueprints. Once sketches are used to generate a solid feature, they are automatically hidden. Constraints are only visible in Sketch edit mode. If you only need to produce 2D views for print, and don't want to create 3D models, check out the Draft workbench. Unlike Sketcher elements, Draft objects don't use constraints; they are simple shapes defined at the moment of creation. Both Draft and Sketcher can be used for 2D geometry drawing, and 3D solid creation, although their preferred use is different; the Sketcher is normally used together with Part and PartDesign to create solids; Draft is normally used for simple planar drawings over a grid, as when drawing an architectural floor plan; in these situations Draft is mostly used together with the Arch Workbench. The tool Draft2Sketch converts a Draft object to a Sketch object, and vice versa; many tools that require a 2D element as input work with either type of object as an internal conversion is done automatically.

Sketching Workflow

A Sketch is always 2-dimensional (2D). To create a solid, a 2D Sketch of a single enclosed area is created and then either Padded or Revolved to add the 3rd dimension, creating a 3D solid from the 2D Sketch. If a Sketch has segments that cross one another, places where a Point is not directly on a segment, or places where there are gaps between endpoints of adjacent segments, Pad or Revolve won't create a solid. Sometimes a Sketch which contains lines which cross one another will work for a simple operation such as Pad, but later operations such as Linear Pattern will fail. It is best to avoid crossing lines. The exception to this rule is that it doesn't apply to Construction (blue) Geometry. Inside the enclosed area we can have smaller non-overlapping areas. These will become voids when the 3D solid is created. Once a Sketch is fully constrained, the Sketch features will turn green; Construction Geometry will remain blue. It is usually "finished" at this point and suitable for use in creating a 3D solid. However, once the Sketch dialog is closed it may be worthwhile going to Check geometry to ensure there are no features in the Sketch which may cause later problems.

Tools

The Sketcher Workbench tools are all located in the Sketch menu that appears when you load the Sketcher Workbench.

General

New sketch: Creates‎ a new sketch on a selected face or plane. If no face is selected while this tool is executed the user is prompted to select a plane from a pop-up window. Edit sketch: Edit the selected Sketch. This will open the Sketcher Dialog. Leave sketch: Leave the Sketch editing mode. View sketch: Sets the model view perpendicular to the sketch plane. View section: Creates a section plane that temporarily hides any matter in front of the sketch plane. Map sketch to face: Maps a sketch to the previously selected face of a solid. Reorient sketch: Allows you to attach the sketch to one of the main planes. Validate sketch: Verify the tolerance of different points and adjust them. Merge sketches: Merge two or more sketches. Mirror sketch: Mirror a sketch along the x-axis, the y-axis or the origin. Stop operation: When in edit mode, stop the current operation, whether that is drawing, setting constraints, etc.

Sketcher geometries

These are tools for creating objects. Point: Draws a point. Line: Draws a line segment between 2 points. Lines are infinite regarding certain constraints. Create an arc: This is an icon menu in the Sketcher toolbar that holds the following commands: Arc: Draws an arc segment from center, radius, start angle and end angle. Arc by 3 points: Draws an arc segment from two endpoints and another point on the circumference. Create a circle: This is an icon menu in the Sketcher toolbar that holds the following commands: Circle: Draws a circle from center and radius. Circle by 3 points: Draws a circle from three points on the circumference. Create a conic: The sketcher provides the following conical sections. Unlike B-splines they can be used with all sorts of constraints such as Tangent, Point On Object, or Perpendicular. Ellipse by center: Draws an ellipse by center point, major radius point and minor radius point. Ellipse by 3 points: Draws an ellipse by major diameter (2 points) and minor radius point. Arc of ellipse: Draws an arc of ellipse by center point, major radius point, starting point and ending point. Arc of hyperbola: Draws an arc of hyperbola. Arc of parabola: Draws an arc of parabola. Create a B-spline: This is an icon menu in the Sketcher toolbar that holds the following commands: Create B-spline: Draws a B-spline curve by its control points. Create periodic B-spline: Draws a periodic (closed) B-spline curve by its control points. Polyline (multiple-point line): Draws a line made of multiple line segments. Pressing the M key while drawing a Polyline toggles between the different polyline modes. Create rectangles: This is an icon menu in the Sketcher toolbar that holds the following commands: introduced in version 0.20 Rectangle: Draws a rectangle from 2 opposite points. Centered Rectangle: Draws a rectangle from a central point and an edge point. introduced in version 0.20 Rounded Rectangle: Draws a rounded rectangle from 2 opposite points. introduced in version 0.20 Create regular polygon: This is an icon menu in the Sketcher toolbar that holds the following commands: Triangle: Draws a regular triangle inscribed in a construction geometry circle. Square: Draws a regular square inscribed in a construction geometry circle. Pentagon: Draws a regular pentagon inscribed in a construction geometry circle. Hexagon: Draws a regular hexagon inscribed in a construction geometry circle. Heptagon: Draws a regular heptagon inscribed in a construction geometry circle. Octagon: Draws a regular octagon inscribed in a construction geometry circle. Create Regular Polygon : Draws a regular polygon by selecting the number of sides and picking two points: the center and one corner. Slot: Draws an oval by selecting the center of one semicircle and an endpoint of the other semicircle. Fillet: Makes a fillet between two lines joined at one point. Select both lines or click on the corner point, then activate the tool. Trimming: Trims a line, circle or arc with respect to the clicked point. Extend: Extends a line or an arc to a boundary line, arc, ellipse, arc of ellipse or a point in space. Split: Splits a line or an arc into two, converts a circle into an arc while keeping most of the constraints. introduced in version 0.20 External Geometry: Creates an edge linked to external geometry. CarbonCopy: Copies the geometry of another sketch. Construction Mode: Toggles sketch geometry from/to construction mode. Construction geometry is shown in blue and is discarded outside of Sketch editing mode.

Sketcher constraints

Constraints are used to define lengths, set rules between sketch elements, and to lock the sketch along the vertical and horizontal axes. Some constraints require use of Helper constraints.

Geometric constraints

These constraints are not associated with numeric data. Coincident: Affixes a point onto (coincident with) one or more other points. Point On Object: Affixes a point onto another object such as a line, arc, or axis. Vertical: Constrains the selected lines or polyline elements to a true vertical orientation. More than one object can be selected before applying this constraint. Horizontal: Constrains the selected lines or polyline elements to a true horizontal orientation. More than one object can be selected before applying this constraint. Parallel: Constrains two or more lines parallel to one another. Perpendicular: Constrains two lines perpendicular to one another, or constrains a line perpendicular to an arc endpoint. Tangent: Creates a tangent constraint between two selected entities, or a co-linear constraint between two line segments. A line segment does not have to lie directly on an arc or circle to be constrained tangent to that arc or circle. Equal: Constrains two selected entities equal to one another. If used on circles or arcs their radii will be set equal. Symmetric: Constrains two points symmetrically about a line, or constrains the first two selected points symmetrically about a third selected point. Block: it blocks an edge from moving, that is, it prevents its vertices from changing their current positions. It should be particularly useful to fix the position of B-Splines. See the Block Constraint forum topic.

Dimensional constraints

These are constraints associated with numeric data, for which you can use the expressions. The data may be taken from a spreadsheet. Lock: Constrains the selected item by setting vertical and horizontal distances relative to the origin, thereby locking the location of that item. These constraint distances can be edited later. Horizontal distance: Fixes the horizontal distance between two points or line endpoints. If only one item is selected, the distance is set to the origin. Vertical distance: Fixes the vertical distance between 2 points or line endpoints. If only one item is selected, the distance is set to the origin. Distance: Defines the distance of a selected line by constraining its length, or defines the distance between two points by constraining the distance between them. Radius: Defines the radius of a selected arc or circle by constraining the radius. Diameter: Defines the diameter of a selected arc or circle by constraining the diameter. Radiam: Automatically defines radius/diameter of a selected arc or circle (weight for a B-spline pole, diameter for a complete circle, radius for an arc) introduced in version 0.20 Angle: Defines the internal angle between two selected lines.

Special constraints

Snell's Law: Constrains two lines to obey a refraction law to simulate the light going through an interface. Internal alignment: Aligns selected elements to selected shape (e.g. a line to become major axis of an ellipse).

Constraint tools

The following tools can be used the change the effect of constraints: Toggle driving/reference constraint: Toggles the toolbar or the selected constraints to/from reference mode. Activate/Deactivate constraint: Enable or disable an already placed constraint. introduced in version 0.19

Sketcher tools

Select solver DOFs: Highlights in green the geometry with degrees of freedom (DOFs), i.e. not fully constrained. Close Shape: Creates a closed shape by applying coincident constraints to endpoints. Connect Edges: Connect sketcher elements by applying coincident constraints to endpoints. Select Constraints: Selects the constraints of a sketcher element. Select Elements Associated with constraints: Select sketcher elements associated with constraints. Select Redundant Constraints: Selects redundant constraints of a sketch. Select Conflicting Constraints: Selects conflicting constraints of a sketch. Show/Hide internal geometry: Recreates missing/deletes unneeded internal geometry of a selected ellipse, arc of ellipse/hyperbola/parabola or B-spline. Select Origin: Selects the origin of a sketch. Select Vertical Axis: Selects the vertical axis of a sketch. Select Horizontal Axis: Selects the horizontal axis of a sketch. Symmetry: Copies a sketcher element symmetrical to a chosen line. Clone: Clones a sketcher element. Copy: Copies a sketcher element. Move: Moves the selected geometry taking as reference the last selected point. Rectangular Array: Creates an array of selected sketcher elements. Remove Axes Alignment: Remove axes alignment while trying to preserve the constraint relationship of the selection. introduced in version 0.20 Delete All Geometry: Deletes all geometry from the sketch. Delete All Constraints: Deletes all constraints from the sketch.

Sketcher B-spline tools

Show/hide B-spline degree Show/hide B-spline control polygon Show/hide B-spline curvature comb Show/hide B-spline knot multiplicity Show/hide B-spline control point weight, introduced in version 0.19 Convert geometry to B-spline Increase B-spline degree Decrease B-spline degree, introduced in version 0.19 Increase knot multiplicity Decrease knot multiplicity

Sketcher virtual space

Switch Virtual Space: Allows you to hide all constraints of a sketch and make them visible again.

Preferences

Preferences: Preferences for the Sketcher workbench.

Best Practices

Every CAD user develops his own way of working over time, but there are some useful general principles to follow. A series of simple sketches is easier to manage than a single complex one. For example, a first sketch can be created for the base 3D feature (either a pad or a revolve), while a second one can contain holes or cutouts (pockets). Some details can be left out, to be realized later on as 3D features. You can choose to avoid fillets in your sketch if there are too many, and add them as a 3D feature. Always create a closed profile, or your sketch won't produce a solid, but rather a set of open faces. If you don't want some of the objects to be included in the solid creation, turn them to construction elements with the Construction Mode tool. Use the auto constraints feature to limit the number of constraints you'll have to add manually. As a general rule, apply geometric constraints first, then dimensional constraints, and lock your sketch last. But remember: rules are made to be broken. If you're having trouble manipulating your sketch, it may be useful to constrain a few objects first before completing your profile. If possible, center your sketch to the origin (0,0) with the lock constraint. If your sketch is not symmetric, locate one of its points to the origin, or choose nice round numbers for the lock distances. In v0.12, external constraints (constraining the sketch to existing 3D geometry like edges or to other sketches) are not implemented. This means that to locate following sketches geometry to your first sketch, you'll need to set distances relative to your first sketch manually. A lock constraint of (25,75) from the origin is more easily remembered than (23.47,73.02). If you have the possibility to choose between the Length constraint and the Horizontal or Vertical Distance constraints, prefer the latter. Horizontal and Vertical Distance constraints are computationally cheaper. In general, the best constraints to use are: Horizontal and Vertical Constraints; Horizontal and Vertical Length Constraints; Point-to-Point Tangency. If possible, limit the use of these: the general Length Constraint; Edge-to-Edge Tangency; Fix Point Onto a Line Constraint; Symmetry Constraint. If in doubt about the validity of a sketch once it is complete (features turn green), close the Sketcher dialog, switch to the Check geometry.

Tutorials

Sketcher tutorial by chrisb. This is a 70-page long PDF document that serves as a detailed manual for the sketcher. It explains the basics of Sketcher usage, and goes into a lot of detail about the creation of geometrical shapes, and each of the constraints. Basic Sketcher Tutorial for beginners Sketcher Micro Tutorial - Constraint Practices Sketcher requirement for a sketch Minimum requirement for a sketch and Complete determination of a sketch

Scripting

The Sketcher scripting page contains examples on how to create constraints from Python scripts.


Spreadsheet Workbench

A spreadsheet with certain cells filled with text and quantities

Tools

Create sheet: create a new spreadsheet. Import: import a CSV file into a spreadsheet. Export: export a CSV file from a spreadsheet. Merge cells: merge selected cells. Split cell: split previously merged cells. Align left: align the contents of selected cells to the left. Align center: align the contents of selected cells to the center horizontally. Align right: align the contents of selected cells to the right. Align top: align the contents of selected cells to the top. Align vertical center: align the contents of selected cells to the center vertically. Align bottom: top align the contents of selected cells to the bottom. Style bold: set the contents of selected cells to bold. Style italic: set the contents of selected cells to italic. Style underline: set the contents of selected cells to underlined. Set alias: set the alias for a selected cell. Black and White set the foreground and the background colors of selected cells.

Preferences

Preferences: the preferences for the Spreadsheet Workbench. introduced in version 0.20

Insert and remove rows and columns

Rows and columns can be inserted or removed by right-clicking a row or column header and selecting the appropriate option from the contex menu. It is possible to select multiple rows or columns first. Either by holding down the Ctrl key while selecting the headers, or by holding down the left mouse button and dragging. In FreeCAD version 0.19 and earlier rows are inserted above the selected rows, and colomns on the left of the selected columns. In FreeCAD version 0.20 you can specify the insertion side. Note that removing rows or columns with data can break the spreadsheet and your model if it relies on the spreadheet. You are not prewarned if this happens.

Cut and copy-paste cells

Cut and copy-paste operations can be used on cells in FreeCAD spreadsheets. You can use the normal shortcuts for these operations: Ctrl+X, Ctrl+C and Ctrl+V respectively. To select multiple cells hold down the Ctrl key while selecting, or hold down the left mouse button and drag to select a rectangular cell range. The cut and copy operations store the contents and properties of the cells on the Clipboard. The paste operation writes the data in such a way that the content of the top left cell of the stored data is dropped in the active cell. Other stored content is placed relative to that cell. Formulas are updated accordingly. Note that removing cells with data can break the spreadsheet and your model if it relies on the spreadheet. You are not prewarned if this happens. In FreeCAD version 0.19 and earlier there is a bug that can cause FreeCAD to hang if a non-rectangular cell range is pasted. It is advisable to save your work before performing any paste operations.

Cell properties

The properties of a spreadsheet cell can be edited with a right-click on a cell. The following dialog pops up: As indicated by the tabs, the following properties can be changed: Color: Text color and background color Alignment: Text horizontal and vertical alignment Style: Text style: bold, italic, underline Units: Display units for this cell. Please read the Units section below. Alias: Define an alias for this cell. This alias can be used in cell formulas and also in general expressions; see section Spreadsheet data in expressions for more information.

Cell expressions

A spreadsheet cell may contain arbitrary text or an expression. Technically, expressions must start with an equals '=' sign. However, the spreadsheet attempts to be intelligent; if you enter what looks like an expression without the leading '=', one will be added automatically. Cell expressions may contain numbers, functions, references to other cells, and references to properties of the model (But see Current limitations below). Cells are referenced by their column (CAPITAL letter) and row (number). A cell may also be referenced by its alias-name (below). Example: B4 + A6 Note: Cell expressions are treated by FreeCAD as programming code. Therefore, when you edit a cell the content you see that it is not following your display settings: the decimal separator is always a dot the number of displayed decimals can differ from your preferences settings References to objects in the model are explained under References to CAD-data below. Using spreadsheet cell values to define model properties are explained under Spreadsheet data in expressions below. For more information on expressions and the available functions, see Expressions.

Interaction between spreadsheets and the CAD model

Data in the cells of a spreadsheet may be used in CAD model parameter expressions. Thus, a spreadsheet may be used as the source for parameter values used throughout a model, effectively gathering the values in one place. When values are changed in the spreadsheet, they are propagated throughout the model. Similarly, properties from CAD model objects may be used in expressions in spreadsheet cells. This allows use of object properties like volume or area in the spreadsheet. If the name of an object in the CAD model is changed, the change will automatically be propagated to any references in spreadsheet expressions using the name which was changed. More than one spreadsheet may be used in a document. A spreadsheet can be identified using either its name or its label. FreeCAD will automatically assign a unique name to a spreadsheet when it is created. These names follow the pattern Spreadsheet, Spreadsheet001, Spreadsheet002 and so on. The name can not be changed manually, and it is not visible in the properties of the spreadsheet. It can be used to refer to the spreadsheet in an Expression (see Spreadsheet data in expressions below.) The label of a spreadsheet is automatically set to the name of the spreadsheet upon creation. Unlike the name, the label can be changed, for example in the properties panel or using the context menu action Rename. Note that the label of a spreadsheet within a document has to be unique; if you try to change the label to a label already used by another spreadsheet, FreeCAD will not accept the new label. FreeCAD checks for cyclic dependencies. See Current limitations.

References to CAD-data

As indicated above, one can reference data from the CAD model in spreadsheet expressions. Computed expressions in spreadsheet cells start with an equals ('=') sign. However, the spreadsheet entry mechanism attempts to be smart. An expression may be entered without the leading '='; if the string entered is a valid expression, an '=' is automatically added when the final Enter is typed. If the string entered is not a valid expression (often the result of entering something with the wrong case, e.g. "MyCube.length" instead of "MyCube.Length"), no leading '=' is added and it is treated as simply a text string. Note: The above behavior (auto insert of '=') has some unpleasant ramifications: If you want to keep a column of names corresponding to the alias-names in an adjacent column of values, you must enter the name in the label column before giving the cell in the value column its alias-name. Otherwise, when you enter the alias-name in the label column the spreadsheet will assume it is an expression and change it to "=<alias-name>"; and the displayed text will be the value from the <alias-name> cell. If you make an error when entering the name in the label column and wish to correct it, you cannot simply change it to the alias-name. Instead, you must first change the alias-name to something else, then fix the text name in the label column, then change the alias-name in the value column back to its original. One way to side-step these issues is to prefix text labels corresponding to alias-names with a fixed string, thereby making them different. Note that "_" will not work, as it is converted to "=". However, a blank, while invisible, will work. The following table shows some examples assuming the model has a feature named "MyCube":
CAD-Data Cell in Spreadsheet Result
Parametric Length of a Part-Workbench Cube =MyCube.Length Length with units mm
Volume of the Cube =MyCube.Shape.Volume Volume in mm³ without units
Type of the Cube-shape =MyCube.Shape.ShapeType String: Solid
Label of the Cube =MyCube.Label String: MyCube
x-coordinate of center of mass of the Cube =MyCube.Shape.CenterOfMass.x x-coordinate in mm without units

Spreadsheet data in expressions

In order to use spreadsheet data in other parts of FreeCAD, you will usually create an Expression that refers to the spreadsheet and the cell that contains the data you want to use. You can identify spreadsheets by name or by label, and you can identify the cells by position or by alias. Autocompletion is available for all forms of referencing.
Spreadsheet by Name Spreadsheet by Label
Cell by Position =Spreadsheet042.B5 =<<MySpreadsheet>>.B5
Cell by Alias =Spreadsheet042.MyAlias =<<MySpreadsheet>>.MyAlias
The recommended way to refer to spreadsheet data is to use the spreadsheet label and cell alias name. For a more in-depth explanation of the pros and cons of the addressing modes, see the expanded section below. Using the spreadsheet label has the advantage that it can be freely changed to describe the contents of the spreadsheet. It is also easier to identify the spreadsheet that is being used since the text in the expression matches the label shown in the model and property views. If you decide to change the label of a spreadsheet, existing references to the contents of the spreadsheet will be updated, so you won't break your expressions by renaming the spreadsheet. The internal name of the spreadsheet is not readily available anywhere except within the expression editor, so if you use the internal name and later decide to rename the spreadsheets, you might have a hard time tracing your expression data back to its source. Be aware that when you create a new spreadsheet, the name and the label are the same, so it is easy to accidentally use the spreadsheet name instead of the label. A simple way to avoid this is to give the spreadsheet a meaningful name before starting to use it in expressions. While you may use the row and column number in an expression to reference a cell, best practice is to give the cell an alias name and use that. See Cell Properties above on how to set the alias. For example, if the data in cell B1 contained the length parameter for an object, an alias name of MyObject_Length would allow the value to be referred to as <<MyParams>>.MyObject_Length instead of Spreadsheet.B1. Besides being much easier to read and understand, alias names are also much easier to change if you decide to adjust the structure of your spreadsheet. Using an alias also has the advantage that it is reasier to see which cells are used to control other parts of the document. Note that FreeCAD will automatically adjust the positional references in expressions if you insert or remove rows and columns in the spreadsheet, so even if you use row and column numbers in an expression, you can insert rows and columns without breaking the references to the surrounding cells.

Complex models and recomputes

Editing a spreadsheet will trigger a recompute of the 3D model, even if the changes do not affect the model. For a complex model a recompute can take a long time, and having to wait after every single edit is of course quite annoying. There are three solutions to deal with this:
    Temporarily skip recomputes: In the document that contains the spreadsheet. Select the Skip recomputes option from the context menu. There is a big disadvantage to this solution. New values entered in the spreadsheet will not be displayed until the document is recomputed. Instead #PENDING is shown. You can either recompute manually, using the Std Refresh command, or disable Skip recomputes when you are done editing. Use a macro to automatically skip recomputes while editing a spreadsheet: Download and run skipSheet.FCMacro. This solution saves a few steps compared to the first solution, but also has the mentioned disadvantage. Put the spreadsheet in a separate FreeCAD file: You can reference spreadsheet data from an external .FCStd file with this syntax: =NameOfFile#<<MySpreadsheet>>.MyAlias. The advantage of having the spreadsheet in another file over switching off recomputes is that the spreadsheet itself does get recomputed. The disadvantage is that the model won't automatically recompute after changes to the spreadsheet. In the scenario where you first open the 'spreadsheet' file, change one or more values and then open the 'model' file, there won't be any indication that the model needs to be recomputed. But if both files are open the Std Refresh icon will update correctly for the 'model' file after changes to the 'spreadsheet' file.

Units

The Spreadsheet has a notion of dimension (units) associated with cell values. A number entered without an associated unit has no dimension. The unit should be entered immediately following the number value, with no intervening space. If a number has an associated unit, that unit will be used in all calculations. For example, the multiplication of two lengths with the unit mm gives an area with the unit mm². If a cell contains a value which represents a dimension, it should be entered with its associated unit. While in many simple cases one can get by with a dimensionless value, it is unwise to not enter the unit. If a value representing a dimension is entered without its associated unit, there are some sequences of operations which cause FreeCAD to complain of incompatible units in an expression when it appears the expression should be valid. (This may be better understood by viewing this thread in the FreeCAD forums.) You can change the units displayed for a cell value using the properties dialog units tab (above). This does not change the value contained in the cell; it only converts the existing value for display. The value used for calculations does not change, and the results of formulas using the value do not change. For example, a cell containing the value "5.08cm" can be displayed as "2in" by changing the units tab value to "in". A dimensionless number cannot be changed to a number with a unit by the cell properties dialog. One can put in a unit string, and that string will be displayed; but the cell still contains a dimensionless number. In order to change a dimensionless value to a value with a dimension, the value itself must be re-entered with its associated unit. Occasionally it may be desirable to get rid of a dimension in an expression. This can be done by multiplying by 1 with a reciprocal unit.

Importing and exporting

CSV format

FreeCAD spreadsheets can be imported and exported to the CSV format which can also be read and written by most other spreadsheet applications such as Microsoft Excel or LibreOffice Calc. See Spreadsheet Import and Spreadsheet Export for more information.

XLSX format

Spreadsheets in the Excel-format XLSX can be imported with the Std Import command or the Std Open command. The following features are supported: All functions that are also available in the FreeCAD spreadsheet. Other functions give an error in the corresponding cell after import. Alias names for cells. More than one sheet in the Excel-spreadsheet. In this case one FreeCAD spreadsheet is created for each Excel sheet. Other functionality is not imported into the FreeCAD spreadsheet.

Printing

To handle the page setup necessary for printing, FreeCAD spreadsheets are printed by inserting them into a TechDraw Spreadsheet View.

Current limitations

FreeCAD checks for cyclic dependencies. By design, that check stops at the level of the spreadsheet object. As a consequence, you should not have a spreadsheet which contains both cells whose values are used to specify parameters to the model, and cells whose values use output from the model. For example, you cannot have cells specifying the length, width, and height of an object, and another cell which references the total volume of the resulting shape. This restriction can be surmounted by having two spreadsheets: one used as a data-source for input parameters to the model and the other used for calculations based on resultant geometry-data.

Scripting basics

import Spreadsheet sheet = App.ActiveDocument.addObject("Spreadsheet::Sheet","MySpreadsheet") sheet.Label = "Dimensions" sheet.set('A1','10mm') sheet.recompute() sheet.get('A1') sheet.setAlias('B1','Diameter') sheet.set('Diameter','20mm') sheet.recompute() sheet.get('Diameter')


TechDraw Workbench

Pages

These are tools for creating Page objects. Insert Default Page: adds a new page using the default template. Insert Page using Template: adds a new page using a selected template. Redraw Page: forces an update of the selected page. introduced in version 0.19

Views

These are tools for creating View objects. Insert View: adds a 2D projection view of an object. Insert Active View: inserts a view of the active 3D view. introduced in version 0.19 Insert Projection Group: invokes a dialog to create many views of an object from multiple directions. Insert Section View: inserts a cross-section view of an existing view. Insert Detail View: inserts a detail view of a portion of an existing view. Insert Draft Workbench Object: inserts a view of a Draft Workbench object. Insert Arch Workbench Object: inserts a view of an Arch Workbench Section Plane object. Insert Spreadsheet View: inserts a view of a Spreadsheet Workbench sheet.

Clips

These are tools to create and manage Clip objects (clipped views). Insert Clip Group: inserts a clip group into a page. Add View to Clip Group: adds an existing view to a clip group. Remove View from Clip Group: removes a view from a clip group.

Decorations

These are tools to decorate pages or views: Hatch Face using Image File: applies a hatch pattern from a file to a face. Apply Geometric Hatch to Face: applies a hatch pattern to a face using an Autodesk PAT specification. Insert SVG Symbol: inserts a symbol from a SVG file into a page. Insert Bitmap Image: inserts a PNG or JPG bitmap image into a page. Turn View Frames On/Off: turns on/off frames and labels surrounding a view.

Dimensions

These are tools for creating and working with Dimension objects. Linear dimensions can be based on two points, on one line, or on two lines. Insert Length Dimension: adds a length dimension. Insert Horizontal Dimension: adds a horizontal length dimension. Insert Vertical Dimension: adds a vertical length dimension. Insert Radius Dimension: adds a radius dimension to a circle or circular arc. Insert Diameter Dimension: adds a diameter dimension to a circle or a circular arc. Insert Angle Dimension: adds an angle dimension between two straight edges. Insert 3-Point Angle Dimension: adds an angle dimension using three vertices. Insert Horizontal Extent Dimension: adds a horizontal extent dimension. introduced in version 0.19 Insert Vertical Extent Dimension: adds a vertical extent dimension. introduced in version 0.19 Link Dimension to 3D Geometry: links an existing dimension to the 3D geometry. Insert Balloon Annotation: adds a "balloon" annotation to a page. introduced in version 0.19 Insert Landmark Dimension: adds a landmark distance dimension. introduced in version 0.19

Annotations

The annotation tools are for "marking up" a drawing with additional information. Insert Annotation: adds a plain text block as annotation. Add Leaderline to View: adds a leaderline to a view. introduced in version 0.19 Insert Rich Text Annotation: adds an rich text block as annotation to a leaderline or a view. introduced in version 0.19 Add Cosmetic Vertex: adds a Vertex which is not part of the source geometry. introduced in version 0.19 Add Midpoint Vertices: adds Cosmetic Vertices at midpoints of selected edges. introduced in version 0.19 Add Quadrant Vertices: adds Cosmetic Vertices at quarter points of selected (circular) edges. introduced in version 0.19 Add Centerline to Faces: adds a centerline to selected face(s). introduced in version 0.19 Add Centerline between 2 Lines: adds a centerline between 2 lines. introduced in version 0.19 Add Centerline between 2 Points: adds a centerline between 2 points. introduced in version 0.19 Add Cosmetic Line Through 2 points: adds a cosmetic line connecting 2 vertices. introduced in version 0.19 Remove Cosmetic Object: removes cosmetic objects from a page. introduced in version 0.19 Change Appearance of Lines: changes the appearance of selected line(s). introduced in version 0.19 Show/Hide Invisible Edges: shows/hides invisible lines/edges in a view. introduced in version 0.19 Add Welding Information to Leader: adds welding specifications to an existing leaderline. introduced in version 0.19

Extensions

These are tools to improve your TechDraw drawings. Some of these tools have yet to be released. Attributes and Modifications: Select line Attributes: select style, width and colour of lines. introduced in version 0.20 Extend a line: extend a line at both ends. introduced in version 0.20 Shorten a line: shorten a line at both ends. introduced in version 0.20 Align horizontal: align a horizontal dimension chain. introduced in version 0.20 Change line Attributes: change style, width and colour of lines. introduced in version 0.20 Centerlines and Threading: Draw circle centerlines: adds centerlines to circles and arcs. introduced in version 0.20 Draw bolt circle centerlines: draw the centerlines of a bolt circle. introduced in version 0.20 Create vertex(es) at intersection: create the vertexes at intersection of lines. introduced in version 0.20 Draw a cosmetic circumference: draw a cosmetic circumference using center and radius vertex. introduced in version 0.20 Draw an arc rotating math. positive: draw an arc rotating math. positive. introduced in version 0.20 Draw a perpendicular line: draw a line perpendicular to another line through a vertex. introduced in version 0.20 Draw a parallel line: draw a line parallel to another line through a vertex. introduced in version 0.20 Cosmetic thread hole side view: adds a symbolic thread to the side view of a hole. introduced in version 0.20 Cosmetic thread bolt side view: adds a symbolic thread to the side view of a bolt. introduced in version 0.20 Cosmetic thread hole bottom view: adds symbolic threads to the bottom view of holes. introduced in version 0.20 Cosmetic thread bolt bottom view: adds symbolic threads to the bottom view of bolts. introduced in version 0.20 Dimensions: Horizontal Series: create a horizontal dimension chain. introduced in version 0.20

Export

These are tools for exporting pages to other applications. Export Page as SVG: saves the current page as SVG file. Export Page as DXF: saves the current page as DXF file.

Additional features

Line Groups: to control the appearance of various types of lines. Templates: the default templates defined for the drawing pages. Hatching: explanation of the different hatching techniques. Geometric dimensioning and tolerancing: explanation on how to achieve geometric dimensioning and tolerancing.

Preferences

Preferences: preferences for the default values of the drawing page such as projection angle, colors, text sizes, and line styles.

Scripting

The TechDraw tools can be used in macros and from the Python console by using two APIs. TechDraw API TechDrawGui API

Limitations

TechDraw drawings and its API are not interchangeable with the Drawing Workbench and its API. It is possible to convert Drawing Pages to TechDraw Pages using a Python script (moveViews.py). It is possible to have both TechDraw and Drawing Pages in the same FreeCAD document, as each page is completely independent from each other. There are minor differences in specifying editable texts in SVG templates compared to the Drawing module. In TechDraw the scaling of the SVG document affects the position of the editable text fields. See the forum discussion TechDraw templates scale for more details. Do not cut, copy and paste TechDraw objects in the tree view as this generally does not work out well.

Tutorials

Basic TechDraw Tutorial: introduction to creating drawings with the TechDraw Workbench. Creating a new template: instructions to create a new page template in Inkscape for using with the TechDraw Workbench. Measurement Of Angles On Holes: instructions for adding centerlines and subsequent angle representations on holes. Miscellaneous: instructions for different settings like center marks, etc. Creating a Pitch Circle: instructions for adding pitch circle Video tutorials by sliptonic TechDraw Workbench Part 1 (Basics), Part 2 (Dimensions), Part 3 (Multiview) TechDraw Workbench Part 4 (Section and Detail), Part 5 (Customizing Templates)


External workbenches

Introduction

External workbenches are those created by power users which haven't been integrated into the main FreeCAD source code. These workbenches aren't supported by the core FreeCAD development team, so they aren't tested to work with every version of FreeCAD. Questions, bug reports, and improvement requests should be made directly to the authors of the workbench. Workbenches marked with can be installed from the Addon Manager. For manual installation see Installing more workbenches. If there are specific instructions or prerequisites for using an external workbench, then these should be noted on the workbench's home page. Workbenches marked with are not recommended for recent versions of FreeCAD. They are obsolete, unmaintained, superseded by a newer workbench, or maybe they don't work with Python 3 or with Qt5. In most cases they should be avoided.

Assembly workbenches

As of FreeCAD 0.19 there is no official assembly workbench. However, several external tools have been created or are in development to manipulate objects to produce assemblies. Note that the assembly workbenches are generally incompatible with each other. If you create an assembly with one of them, you should stick to the original workbench, and not use another assembly workbench in the same document. There are also 'pseudo assembly' workbenches which actually don't use constraints to keep relationships between parts, but simply re-position them in space.

Overview

The table below is organized in topics, but can be reorder by clicking any of the column headers.
Icon Name Topic Description Author Code
ArchTextures Architecture and construction It allows you to add basic, non-photorealistic textures to architectural objects created with the Arch Workbench. furti https://github.com/furti/FreeCAD-ArchTextures
BCFPlugin Architecture and construction It aims to support the BIM Collaboration Format (BCF). podestplatz https://github.com/podestplatz/BCF-Plugin-FreeCAD
BIM Architecture and construction It aims to implement a complete building information modeling (BIM) workflow in FreeCAD. It extends the Arch Workbench, and gathers tools from other workbenches to provide an environment that is convenient to model buildings, and work with IFC files. yorikvanhavre https://github.com/yorikvanhavre/BIM_Workbench
BIMBots Architecture and construction It allows you to upload a FreeCAD model or selected parts of a FreeCAD model to a BIMBots instance (usually a BIMServer with external services enabled), and perform different services and analyses on your model, and read the results in FreeCAD, usually under the form of a text report, or a BCF file. BIMBots https://github.com/opensourceBIM/BIMbots-FreeCAD
Dodo Architecture and construction It provides tools to create frames (trusses, beams) and pipelines (tubes, elbows, flanges), and query those objects. This is the new version of Flamingo, intended for Python 3 and Qt5. oddtopus https://github.com/oddtopus/dodo
Flamingo Architecture and construction It provides tools to create frames (trusses, beams) and pipelines (tubes, elbows, flanges), and query those objects. This is the old version of Dodo, intended for Python 2 and Qt4. You should prefer Dodo for new models. oddtopus https://github.com/oddtopus/flamingo
GeoData Architecture and construction It provides tool to import geographical information from a given point on Earth by its latitude and longitude, of from OpenStreetMap, Google Maps, Bing Map, or Here Map. microelly2 https://github.com/microelly2/geodata
Geomatics Architecture and construction It is partially based on the GeoData. It provides functionality specific to Geomatics or Survey engineering, including importing point files, creating surfaces, creating contours, and creating sections. This is partially migrated to the Trails workbench. HakanSeven12 https://github.com/HakanSeven12/FreeCAD-Geomatics-Workbench
OSE Piping Architecture and construction Create different piping fittings. It supports Flamingo. Ruslan https://github.com/rkrenzler/ose-piping-workbench
Reinforcement Architecture and construction It provides tools for Reinforcement Generation and Detailing. This workbench provides an interface and presets for the creation of common rebar types. And tools to generate rebars bill of material, rebar shape cut list, bar bending schedule, and rebars drawing and dimension. amrit3701 https://github.com/amrit3701/FreeCAD-Reinforcement
SteelColumn Architecture and construction It provides tools for creating complex steel columns assembled from IPE profiles and plates. ebrahimraeyat https://github.com/ebrahimraeyat/momen
Timber Architecture and construction It provides tools to facilitate the design and modeling of wood-frame and structural walls. This workbench is no longer developed nor maintained by its author. j-wiedemann https://github.com/j-wiedemann/FreeCAD-Timber
Trails Architecture and construction It provides functionality specific to transportation engineering (roads and rail). It includes components to perform analysis of curvature. joelgraff https://github.com/joelgraff/freecad.trails
Wood Frame Architecture and construction It provides tools to facilitate the design and modelling of wood-frame and structural walls, as well as cut lists for beams. JeromeL63 https://github.com/JeromeL63/Wood-Frame
A2plus Assembly It provides tools to create multi-part assemblies. It is a fork and extension of the older Assembly2 Workbench, but it is not compatible with it. kbwbe https://github.com/kbwbe/A2plus
Assembly2 Assembly It provides tools to create multi-part assemblies. It is unmaintained since 2016. Consider using A2plus instead. hamish2014 https://github.com/hamish2014/FreeCAD_assembly2
Assembly3 Assembly It is used to perform assembly of different bodies contained in a single file or in multiple documents. It was a testbed for the App Link object that was eventually included in the master code. It is the most complex solution and supports things like interactive kinematics. realthunder https://github.com/realthunder/FreeCAD_assembly3
Assembly4 Assembly It is a solution based on the enhanced expression engine and the App Link object developed in the branch of Assembly3. Assembly4 does not work with a proper constraint solver, instead it uses the expression engine to position bodies with respect to Local Coordinate Systems (LCS). Zolko https://github.com/Zolko-123/FreeCAD_Assembly4
Autoload Customization It is a small extension that allows you to select the workbenches that should be loaded when you start FreeCAD. It can be used in combination with other extensions from the same author such as CommandPanel, PieMenu, and ShortCuts. triplus https://github.com/triplus/Autoload
CommandPanel Customization It is an extension that provides a panel that can be used store tools from different workbenches. triplus https://github.com/triplus/CommandPanel
CubeMenu Customization CubeMenu provides the ability to manage the FreeCAD navigation cube menu structure and overall appearance. triplus https://github.com/triplus/CubeMenu
Glass Customization It is an extension that shows the combo view (tree view and property editor) as a transparent overlay over the 3D view. triplus https://github.com/triplus/Glass
IconThemes Customization It is an extension that provides the ability of changing the icons of the default program. Icon sets aren't provided with this extension; these need to be provided separately. triplus https://github.com/triplus/IconThemes
Launcher Customization It is a small extension that provides a dedicated dialog box to search and launch commands. Instead of clicking on a toolbar button or menu entry, this method of executing commands may be faster for some users. triplus https://github.com/triplus/Launcher
ModernUI Customization Replaces the standard user interface (UI) with feature such as ribbon menus and collapsing/expanding panels on mouse-over. HakanSeven12 https://github.com/HakanSeven12/Modern-UI
NavigationIndicator Customization It is an extension that adds an indicator for the mouse navigation style in the status bar. Since FreeCAD 0.17 this extension is obsolete, as the indicator is included natively in FreeCAD. triplus https://github.com/triplus/NavigationIndicator
PersistentToolbars Customization It is a small extension to keep the toolbars in their locations. Since FreeCAD 0.17 this extension is obsolete, as the functionality is included natively in FreeCAD. triplus https://github.com/triplus/PersistentToolbars
PieMenu Customization It is a small extension that shows a pie menu to select tools or commands when the Tab key is pressed. A pie menu is an interface that appears in Blender and other systems like Android mobile phones to launch commands. triplus https://github.com/triplus/PieMenu
Pluginloader Customization It is a small extension that allows the user to install macros, external workbenches, and other extensions in FreeCAD. Since FreeCAD 0.17 this utility is obsolete, as this functionality is already provided by the Addon Manager. microelly2 https://github.com/microelly2/freecad-pluginloader
RemBench Customization It is a small extension that remembers and automatically activates a workbench based on the document tab that is selected. triplus https://github.com/triplus/RemBench
SearchBar Customization It is an extension that adds a search bar next to the what's this? tool. The search results include tools, objects and preferences. Other mods can extend it by registering a result provider. Suzanne Soy https://github.com/SuzanneSoy/SearchBar
SelectorToolbar Customization It is a small extension that provides a point and click experience for switching workbenches. triplus https://github.com/triplus/SelectorToolbar
ShortCuts Customization It is a small extension that provides a manager and overlay for shortcuts. triplus https://github.com/triplus/ShortCuts
TabBar Customization It is a small extension that adds a window with tabs in order to select workbenches. triplus https://github.com/triplus/TabBar
ToolbarStyle Customization It is a small extension that allows the configuration of toolbars, with icons, text, or both. triplus https://github.com/triplus/ToolbarStyle
MOOC Education It provides an interactive tutorial to learn about FreeCAD directly inside the program. It allows you to evaluate your self-learning. rockn https://framagit.org/freecad-france/mooc-workbench
AirPlaneDesign Engineering It is an experimental workbench to design wings and airplane objects. FredsFactory (a179308) https://github.com/FredsFactory/FreeCAD_AirPlaneDesign
FreeCADTools Engineering It contains tools to create metal profiles, square tubing, z profile, palette, rotation, drawing, and more. Siardeni https://github.com/Siardeni/FreeCADTools
GDML Engineering It contains tools to handle the Geometry Definition Markup Language (GDML). KeithSloan https://github.com/KeithSloan/GDML
GDT Engineering It is a collection of tools to add geometric dimensioning and tolerancing (GDT) labels in 2D and 3D technical drawings. It implements the standard ISO 16792. juanvanyo https://github.com/juanvanyo/FreeCAD-GDT
Glider Engineering It contains tools to design paragliders and kites using the OpenGlider library. booya https://github.com/booya-at/OpenGlider
KicadStepUp Engineering It is aimed at helping both KiCad and FreeCAD users in collaborating with electrical (ECAD) and mechanical (MCAD) design. With FreeCAD it's possible to design a printed circuit board, and push it to KiCad; alternatively, the board can be designed in KiCad, it can be imported by FreeCAD, it can be edited with the Sketcher Workbench, and pushed back into KiCad. The 3D model, boards and enclosure, can be exported to VRML with materials properties for use in KiCad or Blender. easyw https://github.com/easyw/kicadStepUpMod
LCInterlocking Engineering It contains tools to create interlocking parts that can be cut with laser-cutters. Tabs and hinges can be added, and the sketch can be exported to SVG. execuc https://github.com/execuc/LCInterlocking
Maker Workbench Engineering The Maker Workbench is composed of a mechatronic components system and an optic components system. The user can modify these components to customize their own system. David Muñoz https://github.com/URJCMakerGroup/MakerWorkbench
OSE 3D Printer Engineering A workbench for designing 3D printers by Open Source Ecology for Distributive Enterprise. G Roques https://github.com/gbroques/ose-3d-printer-workbench
Pyrate Engineering It is used to design optical lenses. The project aims to provide an optical raytracer for isotropic, homogeneous anisotropic and inhomogeneous isotropic GRIN media. mess42, joha2 https://github.com/mess42/pyrate
Rocket Engineering It provides tools for model and amateur rocket design. Users can quickly and easily create rocket components suitable for 3D printing, CNC milling, or laser cutting DavesRocketShop https://github.com/davesrocketshop/Rocket.git
SheetMetal Engineering It provides tools to design an object made of a folded sheet, such as a metal case or enclosure. The user starts with a flat sheet, then uses tools to extrude and bend the faces of the object until the desired shape is obtained. The body may then be unfolded to obtain the required flat material, and to use as input for mills or laser cutting machines. Shai Seger and Ulrich Brammer https://github.com/shaise/FreeCAD_SheetMetal
Ship Engineering It is used to create structures that are common to ships. It currently is seeking a maintainer. Jose Luis Cercós Pita https://github.com/FreeCAD/freecad.ship
CADExchanger Information and data It is an extension that allows FreeCAD to import and export file formats supported by the commercial "CAD Exchanger" application, such as Rhino 3dm or ACIS sat, and mesh formats like OBJ and STL. yorikvanhavre https://github.com/yorikvanhavre/CADExchanger
dxf_library Information and data It installs the DXF Python importer and exporter. This was required in FreeCAD versions v0.15 and below. This is not needed anymore when using the built-in DXF importer in v0.16 and above. This library is still needed if you wish to explicitly use the Python importer, or if you wish to export directly from the 3D model. Please notice that the built-in importer is faster than the Python importer, but in many cases the Python importer produces better results. yorikvanhavre https://github.com/yorikvanhavre/Draft-dxf-importer
DynamicData Information and data It is an extension that allows creating container objects to hold custom properties of any type that FreeCAD supports, for example, length or placement. These custom properties can then be used in mathematical expressions just like other properties in the Sketcher Workbench or Spreadsheet Workbench. mwganson https://github.com/mwganson/DynamicData
InventorLoader Information and data It is an extension designed to import Autodesk Inventor files. Currently only Parts (IPT) can be displayed, not assemblies (IAM) nor drawings (IDW). As Inventor files contain a complete ACIS model representation, SAT and SAB files can also be imported. Export will not be supported, neither to IPT nor to SAT. jmplonka https://github.com/jmplonka/InventorLoader
ImportNURBS Information and data A workbench to add support for importing 3dm files using open rhino3dm library Noteː This workbench is still under development keithsloan52 https://github.com/KeithSloan/ImportNURBS
Plot Information and data It is a layer on top of the Matplotlib Python module to graph mathematical functions and vectors of points. Jose Luis Cercós Pita https://github.com/FreeCAD/freecad.plot
Reporting Information and data It adds tools to extract information from a FreeCAD document using SQL statements, and show the results in a spreadsheet. The SQL statements can be used from a graphical user interface or from Python scripts. It works in a similar way to the Arch Schedule tool but is more powerful due to the flexibility that SQL provides. furti https://github.com/furti/FreeCAD-Reporting
WebTools Information and data It contains a series of tools to communicate with web services like Git, a BIM server, and Sketchfab. yorikvanhavre https://github.com/yorikvanhavre/WebTools
YAML Information and data It is an extension that adds an importer to load and manipulate objects from YAML files. In this way it's easier to design and check 3D parts before manufacturing. Mambix https://github.com/Mambix/FreeCAD-yaml-workspace
3DfindIT Parts 3DfindIT.com, the engineering search engine for 3D components from CADENAS, provides users with easy access to millions of CAD models from thousands of international manufacturers and a range of intuitive search methods. tsielaff, berndhahnebach https://github.com/cadenasgmbh/3dfindit-freecad-integration
BOLTSFC Parts It is an extension that allows you to use the BOLTS "Open Library for Technical Specifications", which is a collection of objects like nuts, screws, bolts, and so on, parametrically defined. jreinhardt, berndhahnebach https://github.com/berndhahnebach/BOLTSFC
CadQuery Parts It allows users to design parametric 3D CAD models defined by the CadQuery CAD scripting API. It includes a full-featured editor with auto-completion, syntax highlighting, line numbering, and code folding. Example scripts are included. Script variables can be edited dynamically through the use of a parameter dialog. This workbench also includes cqparts, which is a library that adds support for parts and assemblies with constraints on top of CadQuery. jmwright https://github.com/jmwright/cadquery-freecad-module
Fasteners Workbench Parts It is a workbench that provides various fasteners, screws, bolts, nuts, etc., to attach to your model complying with ISO standards. Ulrich Bramar (@ulrich1a) and Shai Seger (@shais) https://github.com/shaise/FreeCAD_FastenersWB
FCGear Parts It is an extension that adds many different gears like cylindric involute, involute rack, cylindric cycloid, spherical involute bevel-gear, and crown gear. looooo https://github.com/looooo/freecad.gears
Frametools Parts It is an extension with tools to create frames and beams, including two intersecting beams, in which one beam is cut by a plane or by another beam. looooo https://github.com/looooo/freecad.frametools
Parts Library Parts It is an extension that downloads a library of parts in STEP format .step or in FreeCAD format .FCStd that can be imported into a document. Users can contribute content to this library by forking the repository, adding their own parts under a permissive CC-BY 3.0 license, and submitting a pull request to merge the new objects. Community https://github.com/FreeCAD/FreeCAD-library
PCB Parts It is a workbench that allows the user to import and create printed circuit boards (PCB) in FreeCAD. It supports layers, colors, transparencies, importing Step and Iges models, and displaying holes and vias. marmni https://github.com/marmni/FreeCAD-PCB
Retr3d Parts It is a framework designed to model and manufacture 3D printable parts starting from electronic waste. The intention of this project is to recycle e-waste, and promote 3D printing, especially in developing economies. Maaphoo https://github.com/Maaphoo/Retr3d
Stemfie Workbench Parts It is a workbench that generates a set of parametric parts for the Stemfie Project. Stemfie Community https://github.com/bilbaomakers/StemfieWB
Symbols Library Parts It is an extension that downloads a library of SVG symbols that can be used in FreeCAD, particularly in the TechDraw Workbench to produce technical documentation. Users can contribute content to this library by forking the repository, adding their own symbols under a permissive CC-BY 3.0 license, and submitting a pull request to merge the new objects. Community https://github.com/FreeCAD/FreeCAD-symbols
ThreadProfile Parts It provides tools to create parametric 2D thread profiles compatible with extrusion tools in Part and PartDesign workbenches. mwganson https://github.com/mwganson/ThreadProfile
Pivy_trackers Programming Pivy_trackers provides a Python developer with an easy way to directly manipulate the Coin3D scenegraph by generating specific scenegraph node structures which are then inserted and accessed though the pivy_tracker classes. joelgraff https://github.com/joelgraff/pivy_trackers
Animation Pseudo-assembly It contains many tools to simulate movement of parts, create sequences of pictures, and thus produce an animation. The position and rotation of objects can be changed at different times, but also other properties like visibility, transparency, shape color, and camera position. microelly2 https://github.com/microelly2/Animation
ExplodedAssembly Pseudo-assembly It allows creating exploded views and animations of assemblies. It was previously known as "ExplodedAnimation". JMG1 https://github.com/JMG1/ExplodedAssembly
Lattice2 Pseudo-assembly It provides tools for working with placements and arrays of placements. It is a sort of assembly workbench but there are no constraints nor relationships. Instead, the workbench focuses in arrays of placements that can be generated, combined, transformed, superimposed, and populated with shapes. It can also create exploded assemblies. DeepSOIC https://github.com/DeepSOIC/Lattice2
Manipulator Pseudo-assembly It is aimed at helping users in aligning, moving, rotating, and measuring 3D objects through a friendly graphical interface. easyw https://github.com/easyw/Manipulator
Part-o-magic Pseudo-assembly It is an experimental workbench that provides some improvements to Std Part and PartDesign Body containers (automatic grouping, visibility automation, etc.), in order to work with documents that have multiple parts with deep feature hierarchies. It provides a Body-like container for the Part Workbench, and for other workbenches that produce solid shapes. Part-o-magic does not provide assembly constraints, but the tools included may be useful in conjunction with a true assembly workbench. DeepSOIC https://github.com/DeepSOIC/Part-o-magic
Workfeature Pseudo-assembly It provides tools to produce different points, axes, and planes, in order to facilitate the creation of assemblies. This workbench is based on the older Workfeatures macro, which was hosted in the macros recipes page. Currently, the macro has a bit more functionality than the workbench, but eventually the workbench will integrate all existing tools of the macro. They also differ in the graphical user interface; the macro creates a panel next to the tree view and the task panel, while the workbench provides its tools in toolbars, just like other workbenches. Rentlau https://github.com/Rentlau/WorkFeature-WB
Kerkythea Rendering It adds a simple exporter to produce XML files for use with the Kerkythea freeware renderer. marmni https://github.com/marmni/FreeCAD-Kerkythea/blob/master/exportToKerkythea.FCMacro
POV-Ray-Rendering Rendering It creates renderings of your FreeCAD model and is very easy to use but also offers all options for advanced users. The_Raytracers https://github.com/TheRaytracers/freecad-povray-render
Render Rendering It can produce high-quality rendered images, using open-source external rendering engines like Pov-ray, Luxrender, and Appleseed. Render is a replacement for the Raytracing Workbench, and uses the same templates so they are compatible. In the future Render may also support Kerkythea, Blender's EEVEE, and OpenCascade's CadRays engines. yorikvanhavre https://github.com/FreeCAD/FreeCAD-render
3D Printing Tools Shapes It has tools to do small changes to meshes imported from external files like STL. mark1791 https://github.com/mark1791/3D_Printing_Tools
Cura Engine Shapes It is an extension that integrates CuraEngine into FreeCAD in order to facilitate gcode generation for 3D printing. This addon is unmaintained since 2014 and no longer works with recent versions of CuraEngine. cblt2l https://github.com/cblt2l/FreeCAD-CuraEngine-Plugin
CurvedShapes Shapes It has tools to create 3D curves from 2D profiles chbergmann https://github.com/chbergmann/CurvedShapesWorkbench
Curves Shapes It is a collection of tools to create and edit NURBS curves and surfaces. tomate44 (Chris_G) https://github.com/tomate44/CurvesWB
Defeaturing Shapes It provides tools to edit STEP objects to remove features like holes, faces, and edges, and perform some operations with the simplified objects. easyw https://github.com/easyw/Defeaturing_WB
Design456 Shapes Direct modeling tools for FreeCAD. Mariwan Jalal https://github.com/MariwanJ/Design456
Drawing Dimensioning Shapes It adds dimensioning and annotation tools to the Drawing Workbench. It is deprecated since FreeCAD 0.17. Consider using TechDraw Workbench instead. hamish2014 https://github.com/hamish2014/FreeCAD_drawing_dimensioning
Lithophane Shapes It is an extension to convert a provided image to a "lithophane" for 3D printing. A lithophane is an image that can only be seen properly when illuminated from behind. furti https://github.com/furti/FreeCAD-Lithophane
MeshRemodel Shapes It provides tools to help re-create or re-model imported mesh objects to obtain a solid shape. The workflow is to create points from the mesh's vertices, and use those to create sketches, which can then be extruded. mwganson https://github.com/mwganson/MeshRemodel
Nurbs Shapes It is a collection of scripts for managing freeform surfaces and curves. microelly2 https://github.com/microelly2/freecad-nurbs
Pyramids and Polyhedrons Workbench Shapes It has tools for generating pyramids, regular polyhedra and geodesic speres, fully scalable and usable like regular bodies. eddyverl https://github.com/eddyverl/FreeCAD-Pyramids-and-Polyhedrons
Reconstruction Shapes It provides utilities to reconstruct models from images. microelly2 https://github.com/microelly2/reconstruction
Silk Shapes It is a collection of NURBS surface modeling tools focused on low degree and seam continuity. Silk is the new name of the NURBSlib-EVM project. edwardvmills https://github.com/edwardvmills/Silk
Slic3r-tools Shapes It allows exporting parts, and opening the resulting STL in Slic3r. You can set up a default print profile, and directly get information about the resources that would be used to 3D print it, as well as quickly generate the .gcode file. limikael https://github.com/limikael/freecad-slic3r-tools
SlopedPlanesMacro Shapes It allows you to build figures controlling the slopes of the faces of objects. Damian Caceres Moreno https://github.com/luzpaz/SlopedPlanesMacro
Cfd Simulation It provides a graphical interface to the OpenFOAM solver to perform computational fluid dynamics (CFD) simulations. qingfengxia https://github.com/qingfengxia/Cfd
CfdOF Simulation It is a fork of the Cfd workbench that focuses on ease of use; it is intended for people who are just starting in the world of CFD and OpenFOAM. jaheyns https://github.com/jaheyns/CfdOF
DesignSPHysics Simulation It provides a graphical user interface to DualSPHysics, a fluid dynamics solver using the smoothed particle hydrodynamics (SPH) model. ndrs92 https://github.com/DualSPHysics/DesignSPHysics
EM Simulation It provides a graphical interface for different solvers by FastFieldSolvers. At present it supports the 3D magneto-quasistatic impedance solver FastHenry. Support for the 3D electrostatic capacitance solver FasterCap is ongoing. FastFieldSolvers S.R.L. https://github.com/ediloren/EM-Workbench-for-FreeCAD
FEM FrontISTR Simulation It provides a graphical interface for FrontISTR, an open-source large-scale parallel FEM program for nonlinear structural analysis. kinagaki https://github.com/FrontISTR/FEM_FrontISTR

Translating external workbenches

See the wiki page for more information Translating an external workbench


Introduction to Python

Introduction

This is a short tutorial for those new to Python. Python is an open-source, multiplatform programming language. It has several features that make it different from other programming languages, and very accessible to new users: It has been designed to be to readable by human beings, making it relatively easy to learn and understand. It is interpreted, this means that programs do not need to be compiled before they can be executed. Python code can be executed immediately, even line by line if you wish. It can be embedded in other programs as a scripting language. FreeCAD has an embedded Python interpreter. You can write Python code to manipulate parts of FreeCAD. This is very powerful, it means you can build your very own tools. It is extensible, you can easily plug new modules into your Python installation and extend its functionality. For example, there are modules that allow Python to read and write images, to communicate with Twitter, to schedule tasks to be performed by your operating system, etc. The following is a very basic introduction, and by no means a complete tutorial. But hopefully it will provide a good starting point for further exploration into FreeCAD and its mechanisms. We strongly encourage you to enter the code snippets below into a Python interpreter.

The interpreter

Usually when writing computer programs, you open a text editor or your special programming environment (which is basically a text editor with some additional tools), write your program, then compile and execute. Often one or more errors were made during entry, so your program won't work. You may even get an error message telling you what went wrong. Then you go back to your text editor, correct the mistakes, run again, repeating until your program works as intended. In Python that whole process can be done transparently inside the Python interpreter. The interpreter is a Python window with a command prompt, where you can simply type Python code. If you have installed Python on your computer (download it from the Python website if you are on Windows or Mac, install it from your package repository if you are on GNU/Linux), you will have a Python interpreter in your start menu. But, as already mentioned, FreeCAD also has a built-in Python interpreter: the Python console. The FreeCAD Python console If you don't see it, click on View → Panels → Python console. The Python console can be resized and also undocked. The interpreter shows the Python version, then a >>> symbol which is the command prompt. Writing code in the interpreter is simple: one line is one instruction. When you press Enter, your line of code will be executed (after being instantly and invisibly compiled). For example, try writing this: print("hello") print() is a Python command that, obviously, prints something on the screen. When you press Enter, the operation is executed, and the message "hello" is printed. If you make an error, for example let's write: print(hello) Python will immediately tell you so. In this case Python doesn't know what hello is. The " " characters specify that the content is a string, programming jargon for a piece of text. Without these the print() command doesn't recognize hello. By pressing the up arrow you can go back to the last line of code and correct it. The Python interpreter also has a built-in help system. Let's say we don't understand what went wrong with print(hello) and we want specific information about the command: help("print") You'll get a long and complete description of everything the print() command can do. Now that you understand the Python interpreter, we can continue with the more serious stuff.

Variables

Very often in programming you need to store a value under a name. That's where variables come in. For example, type this: a = "hello" print(a) You probably understand what happened here, we saved the string "hello" under the name a. Now that a is known we can use it anywhere, for example in the print() command. We can use any name we want, we just need to follow some simple rules, such as not using spaces or punctuation and not using Python keywords. For example, we can write: hello = "my own version of hello" print(hello) Now hello is not an undefined any more. Variables can be modified at any time, that's why they are called variables, their content can vary. For example: myVariable = "hello" print(myVariable) myVariable = "good bye" print(myVariable) We changed the value of myVariable. We can also copy variables: var1 = "hello" var2 = var1 print(var2) It is advisable to give meaningful names to your variables. After a while you won't remember what your variable named a represents. But if you named it, for example, myWelcomeMessage you'll easily remember its purpose. Plus your code is a step closer to being self-documenting. Case is very important, myVariable is not the same as myvariable. If you were to enter print(myvariable) it would come back with an error as not defined.

Numbers

Of course Python programs can deal with all kinds of data, not just text strings. One thing is important, Python must know what kind of data it is dealing with. We saw in our print hello example, that the print() command recognized our "hello" string. By using " " characters, we specified that what follows is a text string. We can always check the data type of a variable with the type() command: myVar = "hello" type(myVar) It will tell us the content of myVar is a 'str', which is short for string. We also have other basic data types such as integer and float numbers: firstNumber = 10 secondNumber = 20 print(firstNumber + secondNumber) type(firstNumber) Python knows that 10 and 20 are integer numbers, so they are stored as 'int', and Python can do with them everything it can do with integers. Look at the results of this: firstNumber = "10" secondNumber = "20" print(firstNumber + secondNumber) Here we forced Python to consider that our two variables are not numbers but pieces of text. Python can add two pieces of text together, although in that case, of course, it won't perform any arithmetic. But we were talking about integer numbers. There are also float numbers. The difference is float numbers can have a decimal part and integer numbers do not: var1 = 13 var2 = 15.65 print("var1 is of type ", type(var1)) print("var2 is of type ", type(var2)) Integers and floats can be mixed together without problems: total = var1 + var2 print(total) print(type(total)) Because var2 is a float Python automatically decides that the result must also be a float. But there are cases where Python does not knows what type to use. For example: varA = "hello 123" varB = 456 print(varA + varB) This results in an error, varA is a string and varB is an integer, and Python doesn't know what to do. However, we can force Python to convert between types: varA = "hello" varB = 123 print(varA + str(varB)) Now that both variables are strings the operation works. Note that we "stringified" varB at the time of printing, but we didn't change varB itself. If we wanted to turn varB permanently into a string, we would need to do this: varB = str(varB) We can also use int() and float() to convert to integer and float if we want: varA = "123" print(int(varA)) print(float(varA)) You must have noticed that we have used the print() command in several ways. We printed variables, sums, several things separated by commas, and even the result of another Python command. Maybe you also saw that these two commands: type(varA) print(type(varA)) have the same result. This is because we are in the interpreter, and everything is automatically printed. When we write more complex programs that run outside the interpreter, they won't print automatically, so we'll need to use the print() command. With that in mind let's stop using it here. From now on we will simply write: myVar = "hello friends" myVar

Lists

Another useful data type is a list. A list is a collection of other data. To define a list we use [ ]: myList = [1, 2, 3] type(myList) myOtherList = ["Bart", "Frank", "Bob"] myMixedList = ["hello", 345, 34.567] As you can see a list can contain any type of data. You can do many things with a list. For example, count its items: len(myOtherList) Or retrieve one item: myName = myOtherList[0] myFriendsName = myOtherList[1] While the len() command returns the total number of items in a list, the first item in a list is always at position 0, so in our myOtherList "Bob" will be at position 2. We can do much more with lists such as sorting items and removing or adding items. Interestingly a text string is very similar to a list of characters in Python. Try doing this: myvar = "hello" len(myvar) myvar[2] Usually what you can do with lists can also be done with strings. In fact both lists and strings are sequences. Apart from strings, integers, floats and lists, there are more built-in data types, such as dictionaries, and you can even create your own data types with classes.

Indentation

One important use of lists is the ability to "browse" through them and do something with each item. For example look at this: alldaltons = ["Joe", "William", "Jack", "Averell"] for dalton in alldaltons: print(dalton + " Dalton") We iterated (programming jargon) through our list with the for in command and did something with each of the items. Note the special syntax: the for command terminates with : indicating the following will be a block of one of more commands. In the interpreter, immediately after you enter the command line ending with :, the command prompt will change to ... which means Python knows that there is more to come. How will Python know how many of the next lines will need to be executed inside the for in operation? For that, Python relies on indentation. The next lines must begin with a blank space, or several blank spaces, or a tab, or several tabs. And as long as the indentation stays the same the lines will be considered part of the for in block. If you begin one line with 2 spaces and the next one with 4, there will be an error. When you have finished, just write another line without indentation, or press Enter to come back from the for in block Indentation also aids in program readability. If you use large indentations (for example use tabs instead of spaces) when you write a big program, you'll have a clear view of what is executed inside what. We'll see that other commands use indented blocks of code as well. The for in command can be used for many things that must be done more than once. It can, for example, be combined with the range() command: serie = range(1, 11) total = 0 print("sum") for number in serie: print(number) total = total + number print("----") print(total) If you have been running the code examples in an interpreter by copy-pasting, you will find the previous block of text will throw an error. Instead, copy to the end of the indented block, i.e. the end of the line total = total + number and then paste in the interpreter. In the interpreter press Enter until the three dot prompt disappears and the code runs. Then copy the final two lines followed by another Enter. The final answer should appear. If you type into the interpreter help(range) you will see: range(...) range(stop) -> list of integers range(start, stop[, step]) -> list of integers Here the square brackets denote an optional parameter. However all are expected to be integers. Below we will force the step parameter to be an integer using int(): number = 1000 for i in range(0, 180 * number, int(0.5 * number)): print(float(i) / number) Another range() example: alldaltons = ["Joe", "William", "Jack", "Averell"] for n in range(4): print(alldaltons[n], " is Dalton number ", n) The range() command also has that strange particularity that it begins with 0 (if you don't specify the starting number) and that its last number will be one less than the ending number you specify. That is, of course, so it works well with other Python commands. For example: alldaltons = ["Joe", "William", "Jack", "Averell"] total = len(alldaltons) for n in range(total): print(alldaltons[n]) Another interesting use of indented blocks is with the if command. This command executes a code block only if a certain condition is met, for example: alldaltons = ["Joe", "William", "Jack", "Averell"] if "Joe" in alldaltons: print("We found that Dalton!!!") Of course this will always print the sentence, but try replacing the second line with: if "Lucky" in alldaltons: Then nothing is printed. We can also specify an else statement: alldaltons = ["Joe", "William", "Jack", "Averell"] if "Lucky" in alldaltons: print("We found that Dalton!!!") else: print("Such Dalton doesn't exist!")

Functions

There are very few standard Python commands and we already know several of them. But you can create your own commands. In fact, most of the additional modules that you can plug into your Python installation do just that, they add commands that you can use. A custom command in Python is called a function and is made like this: def printsqm(myValue): print(str(myValue) + " square meters") printsqm(45) The def() command defines a new function, you give it a name, and inside the parenthesis you define the arguments that the function will use. Arguments are data that will be passed to the function. For example, look at the len() command. If you just write len(), Python will tell you it needs an argument. Which is obvious: you want to know the length of something. If you write len(myList) then myList is the argument that you pass to the len() function. And the len() function is defined in such a way that it knows what to do with this argument. We have done the same thing with our printsqm function. The myValue name can be anything, and it will only be used inside the function. It is just a name you give to the argument so you can do something with it. By defining arguments you also to tell the function how many to expect. For example, if you do this: printsqm(45, 34) there will be an error. Our function was programmed to receive just one argument, but it received two, 45 and 34. Let's try another example: def sum(val1, val2): total = val1 + val2 return total myTotal = sum(45, 34) Here we made a function that receives two arguments, sums them, and returns that value. Returning something is very useful, because we can do something with the result, such as store it in the myTotal variable.

Modules

Now that you have a good idea of how Python works, you will need to know one more thing: How to work with files and modules. Until now, we have written Python instructions line by line in the interpreter. This method is obviously not suitable for larger programs. Normally the code for Python programs is stored in files with the .py extension. Which are just plain text files and any text editor (Linux gedit, emacs, vi or even Windows Notepad) can be used to create and edit them. There are several of ways to execute a Python program. In Windows, simply right-click your file, open it with Python, and execute it. But you can also execute it from the Python interpreter itself. For this, the interpreter must know where your program is. In FreeCAD the easiest way is to place your program in a folder that FreeCAD's Python interpreter knows by default, such as FreeCAD's user Mod folder: On Linux it is usually /home/<username>/.FreeCAD/Mod/. On Windows it is %APPDATA%\FreeCAD\Mod\, which is usually C:\Users\<username>\Appdata\Roaming\FreeCAD\Mod\. On Mac OSX it is usually /Users/<username>/Library/Preferences/FreeCAD/Mod/. Let's add a subfolder there called scripts and then write a file like this: def sum(a,b): return a + b print("myTest.py succesfully loaded") Save the file as myTest.py in the scripts folder, and in the interpreter window write: import myTest without the .py extension. This will execute the contents of the file, line by line, just as if we had written it in the interpreter. The sum function will be created, and the message will be printed. Files containing functions, like ours, are called modules. When we write a sum() function in the interpreter, we execute it like this: sum(14, 45) But when we import a module containing a sum() function the syntax is a bit different: myTest.sum(14, 45) That is, the module is imported as a "container", and all its functions are inside that container. This is very useful, because we can import a lot of modules, and keep everything well organized. Basically when you see something.somethingElse, with a dot in between, then this means somethingElse is inside something. We can also import our sum() function directly into the main interpreter space: from myTest import * sum(12, 54) Almost all modules do that: they define functions, new data types and classes that you can use in the interpreter or in your own Python modules, because nothing prevents you from importing other modules inside your module! How do we know what modules we have, what functions are inside and how to use them (that is, what kind of arguments they need)? We have already seen that Python has a help() function. Doing: help("modules") will give us a list of all available modules. We can import any of them and browse their content with the dir() command: import math dir(math) We'll see all the functions contained in the math module, as well as strange stuff named __doc__, __file__, __name__. Every function in a well made module has a __doc__ that explains how to use it. For example, we see that there is a sin() function inside the math module. Want to know how to use it? print(math.sin.__doc__) It may not be evident, but on either side of doc are two underscore characters. And finally one last tip: When working on new or existing code, it is better to not use the FreeCAD macro file extension, .FCMacro, but instead use the standard .py extension. This is because Python doesn't recognize the .FCMacro extension. If you use .py your code can be easily loaded with import, as we have already seen, and also reloaded with importlib.reload(): import importlib importlib.reload(myTest) There is however an alternative: exec(open("C:/PathToMyMacro/myMacro.FCMacro").read())

Starting with FreeCAD

Hopefully you now have a good idea of how Python works, and you can start exploring what FreeCAD has to offer. FreeCAD's Python functions are all well organized in different modules. Some of them are already loaded (imported) when you start FreeCAD. Just try: dir()

Notes

FreeCAD was originally designed to work with Python 2. Since Python 2 reached the end of its life in 2020, future development of FreeCAD will be done exclusively with Python 3, and backwards compatibility will not be supported. Much more information about Python can be found in the official Python tutorial and the official Python reference.


FreeCAD Scripting Basics

Python scripting in FreeCAD

FreeCAD is built from scratch to be totally controlled by Python scripts. Almost all parts of FreeCAD, such as the interface, the scene contents, and even the representation of this content in the 3D views, are accessible from the built-in Python interpreter or from your own scripts. As a result, FreeCAD is probably one of the most deeply customizable engineering applications available today. If you are not familiar with Python, we recommend you search for tutorials on the internet and have a quick look at its structure. Python is a very easy language to learn, especially because it can be run inside an interpreter, where simple commands, right up to complete programs, can be executed on the fly without the need to compile anything. FreeCAD has a built-in Python interpreter. If you don't see the window labeled Python console as shown below, you can activate it under the View → Panels → Python console.

The interpreter

From the interpreter, you can access all your system-installed Python modules, as well as the built-in FreeCAD modules, and all additional FreeCAD modules you installed later. The screenshot below shows the Python interpreter: From the interpreter, you can execute Python code and browse through the available classes and functions. FreeCAD provides a very handy class browser for exploration of the FreeCAD world: When you type the name of a known class followed by a period (meaning you want to add something from that class), a class browser window opens, where you can navigate between available subclasses and methods. When you select something, an associated help text (if it exists) is displayed: So, start here by typing App. or Gui. and see what happens. Another more generic Python way of exploring the content of modules and classes is to use the print(dir()) command. For example, typing print(dir()) will list all modules currently loaded in FreeCAD. print(dir(App)) will show you everything inside the App module, etc. Another useful feature of the interpreter is the possibility to go back through the command history and retrieve a line of code that you already typed earlier. To navigate through the command history, just use Up arrow or Down arrow. By right-clicking in the interpreter window, you also have several other options, such as copy the entire history (useful when you want to experiment with things before making a full script of them), or insert a filename with complete path.

Python Help

In the FreeCAD Help menu, you'll find an entry labeled Automatic python modules documentation, which will open a browser window containing a complete, realtime-generated documentation of all Python modules available to the FreeCAD interpreter, including Python and FreeCAD built-in modules, system-installed modules, and FreeCAD additional modules. The documentation available there depends on how much effort each module developer put into documenting his code, but Python modules have a reputation for being fairly well documented. Your FreeCAD window must stay open for this documentation system to work. The entry Python scripting documentation will give you a quick link to the Power users hub wiki section.

Built-in modules

Since FreeCAD is designed so that it can also be run without a Graphical User Interface (GUI), almost all its functionality is separated into two groups: Core functionality, named App, and GUI functionality, named Gui. These two modules can also be accessed from scripts outside of the interpreter, by the names FreeCAD and FreeCADGui respectively. In the App module you'll find everything related to the application itself, like methods for opening or closing files, and to the documents, like setting the active document or listing their contents. In the Gui module, you'll find tools for accessing and managing Gui elements, like the workbenches and their toolbars, and, more interestingly, the graphical representation of all FreeCAD content. Listing the content of these modules is not very useful because they grow quite fast as FreeCAD develops. But the two browsing tools provided (the class browser and the Python help) should give you complete and up-to-date documentation at any moment.

The App and Gui objects

As already mentioned, in FreeCAD everything is separated into core and representation. This includes the 3D objects. You can access defining properties of objects (called features in FreeCAD) via the App module, and change the way they are represented on screen via the Gui module. For example, a cube has properties that define it (like width, length, height) that are stored in an App object, and representation properties (like faces color, drawing mode) that are stored in a corresponding Gui object. This way of doing things allows a very wide range of uses, like having algorithms work only on the definition part of features, without the need to care about any visual part, or even redirect the content of the document to non-graphical application, such as lists, spreadsheets, or element analysis. For every App object in your document, there exists a corresponding Gui object. In fact the document itself has both an App and a Gui object. This, of course, only applies when you run FreeCAD with its full interface. In the command-line version no GUI exists, so only App objects are available. Note that the Gui part of objects is re-generated every time an App object is marked as 'to be recomputed' (for example when one of its parameters changes), so any changes made directly to the Gui object may be lost. To access the App part of something, you type: myObject = App.ActiveDocument.getObject("ObjectName") where "ObjectName" is the name of your object. You can also type: myObject = App.ActiveDocument.ObjectName To access the Gui part of the same object, you type: myViewObject = Gui.ActiveDocument.getObject("ObjectName") where "ObjectName" is the name of your object. You can also type: myViewObject = App.ActiveDocument.ObjectName.ViewObject If you are in command-line mode and have no GUI, the last line will return None.

The Document objects

In FreeCAD all your work resides inside documents. A document contains your geometry and can be saved to a file. Several documents can be opened at the same time. The document, like the geometry contained inside, has App and Gui objects. The App object contains your actual geometry definitions, while the Gui object contains the different views of your document. You can open several windows, each one viewing your work with a different zoom factor or from a different direction. These views are all part of your document's Gui object. To access the App part of the currently open (active) document, you type: myDocument = App.ActiveDocument To create a new document, type: myDocument = App.newDocument("Document Name") To access the Gui part of the currently open (active) document, you type: myGuiDocument = Gui.ActiveDocument To access the current view, you type: myView = Gui.ActiveDocument.ActiveView

Using additional modules

The FreeCAD and FreeCADGui modules are only responsible for creating and managing objects in the FreeCAD document. They don't actually do anything more such as creating or modifying geometry. This is because that geometry can be of several types, and therefore requires additional modules, each responsible for managing a certain geometry type. For example, the Part Workbench, using the OpenCascade kernel, is able to create and manipulate BRep type geometry. Whereas the Mesh Workbench is able to build and modify mesh objects. In this manner FreeCAD is able to handle a wide variety of object types, that can all coexist in the same document, and new types can easily be added in the future.

Creating objects

Each module has its own way of dealing with geometry, but one thing they usually all can do is create objects in the document. But the FreeCAD document is also aware of the available object types provided by the modules: FreeCAD.ActiveDocument.supportedTypes() will list all possible objects you can create. For example, let's create a mesh (handled by the Mesh module) and a part (handled by the Part module): myMesh = FreeCAD.ActiveDocument.addObject("Mesh::Feature", "myMeshName") myPart = FreeCAD.ActiveDocument.addObject("Part::Feature", "myPartName") The first argument is the object type, the second the name of the object. Our two objects look almost the same: They don't contain any geometry yet, and most of their properties are the same when you inspect them with dir(myMesh) and dir(myPart). Except for one thing, myMesh has a Mesh property and myPart has a Shape property. That is where the Mesh and Part data are stored. For example, let's create a Part cube and store it in our myPart object: import Part cube = Part.makeBox(2, 2, 2) myPart.Shape = cube You could try storing the cube inside the Mesh property of the myMesh object, but it will return an error. That is because each properties is made to store only a certain type. In a Mesh property, you can only save stuff created with the Mesh module. Note that most modules also have a shortcut to add their geometry to the document: import Part cube = Part.makeBox(2, 2, 2) Part.show(cube)

Modifying objects

Modifying an object is done in the same way: import Part cube = Part.makeBox(2, 2, 2) myPart.Shape = cube Now let's change the shape by a bigger one: biggercube = Part.makeBox(5, 5, 5) myPart.Shape = biggercube

Querying objects

You can always look at the type of an object like this: myObj = FreeCAD.ActiveDocument.getObject("myObjectName") print(myObj.TypeId) or check if an object is derived from one of the basic ones (Part Feature, Mesh Feature, etc): print(myObj.isDerivedFrom("Part::Feature")) Now you can really start playing with FreeCAD! For a complete list of available modules and their tools, visit the Category:API section.


Macros

Introduction

Macros are a convenient way to reproduce complex actions in FreeCAD. You simply record actions as you do them, then save those actions under a name, and replay them whenever you want. Since macros are in reality a list of Python commands, you can also edit them, and create very complex scripts. While Python scripts normally have the .py extension, FreeCAD macros should have the .FCMacro extension. A collection of macros written by experienced users is found in the macros recipes page. See the Power users hub to learn more about the Python programming language, and about writing macros. In particular, you should start with these pages: Introduction to Python Python scripting tutorial FreeCAD Scripting Basics

How it works

Enable the console output in the menu Edit → Preferences → General → Macro → Show scripts commands in python console. You will see that in FreeCAD, every action you do, such as pressing a button, outputs a Python command. Those commands are what can be recorded in a macro. The main tool for making macros is the macros toolbar: . On it you have 4 buttons: Record, stop recording, edit and play the current macro. It is very simple to use: Press the record button, you will be asked to give a name to your macro, then perform some actions. When you are done, click the stop recording button, and your actions will be saved. You can now access the macro dialog with the edit button. Macro dialog, listing the macros available in the system There you can manage your macros, delete, edit, duplicate, install or create new ones from scratch. If you edit a macro, it will be opened in an editor window where you can make changes to its code. New macros can be installed using the Addons... button, which links to the Addon Manager.

Example

Press the record button, give a name, let's say "cylinder 10x10", then, in the Part Workbench, create a cylinder with radius = 10 and height = 10. Then, press the "stop recording" button. In the edit macros dialog, you can see the python code that has been recorded, and, if you want, make alterations to it. To execute your macro, simply press the execute button on the toolbar while your macro is in the editor. You macro is always saved to disk, so any change you make, or any new macro you create, will always be available next time you start FreeCAD.

Customizing

Of course it is not practical to load a macro in the editor in order to use it. FreeCAD provides much better ways to use your macro, such as assigning a keyboard shortcut to it or putting an entry in the menu. Once your macro is created, all this can be done via the Tools → Customize menu. This way you can make your macro become a real tool, just like any standard FreeCAD tool. This, added to the power of python scripting within FreeCAD, makes it possible to easily add your own tools to the interface. See Customize Toolbars for a more detailed description.

Creating macros without recording

You can also directly copy/paste python code into a macro, without recording GUI action. Simply create a new macro, edit it, and paste your code. You can then save your macro the same way as you save a FreeCAD document. Next time you start FreeCAD, the macro will appear under the "Installed Macros" item of the Macro menu. See How to install macros for a more detailed description.

Macro repositories

There are two main places for macros. The first one is the official peer-reviewed macro repository on GitHub. The second one is the Macros recipes page from which you can pick some useful macros to add to your FreeCAD installation. Macros from both repositories can be installed via the Addon Manager directly from FreeCAD.

Additional information

Automatically run macro at startup Installing more workbenches

Tutorials

You can manually install extensions, however, it is much simpler to just use the Addon Manager. How to install macros How to install additional workbenches


Topological data scripting

Introduction

Here we will explain to you how to control the Part module directly from the FreeCAD Python interpreter, or from any external script. Be sure to browse the Scripting section and the FreeCAD Scripting Basics pages if you need more information about how Python scripting works in FreeCAD. If you are new to Python, it is a good idea to first read the Introduction to Python.

See also

Part scripting OpenCASCADE

Class diagram

This is a Unified Modeling Language (UML) overview of the most important classes of the Part module:

Geometry

The geometric objects are the building blocks of all topological objects: Geom Base class of the geometric objects. Line A straight line in 3D, defined by starting point and end point. Circle Circle or circle segment defined by a center point and start and end point. Etc.

Topology

The following topological data types are available: Compound A group of any type of topological objects. Compsolid A composite solid is a set of solids connected by their faces. It expands the notions of WIRE and SHELL to solids. Solid A part of space limited by shells. It is three dimensional. Shell A set of faces connected by their edges. A shell can be open or closed. Face In 2D it is part of a plane; in 3D it is part of a surface. Its geometry is constrained (trimmed) by contours. It is two dimensional. Wire A set of edges connected by their vertices. It can be an open or closed contour depending on whether the edges are linked or not. Edge A topological element corresponding to a restrained curve. An edge is generally limited by vertices. It has one dimension. Vertex A topological element corresponding to a point. It has zero dimension. Shape A generic term covering all of the above.

Example: Create simple topology

We will now create a topology by constructing it out of simpler geometry. As a case study we will use a part as seen in the picture which consists of four vertices, two arcs and two lines.

Create geometry

First we create the distinct geometric parts of this wire. Making sure that parts that have to be connected later share the same vertices. So we create the points first: import Part from FreeCAD import Base V1 = Base.Vector(0, 10, 0) V2 = Base.Vector(30, 10, 0) V3 = Base.Vector(30, -10, 0) V4 = Base.Vector(0, -10, 0)

Arc


For each arc we need a helper point: VC1 = Base.Vector(-10, 0, 0) C1 = Part.Arc(V1, VC1, V4) VC2 = Base.Vector(40, 0, 0) C2 = Part.Arc(V2, VC2, V3)

Line


The line segments can be created from two points: L1 = Part.LineSegment(V1, V2) L2 = Part.LineSegment(V3, V4)

Put it all together

The last step is to put the geometric base elements together and bake a topological shape: S1 = Part.Shape([C1, L1, C2, L2])

Make a prism

Now extrude the wire in a direction and make an actual 3D shape: W = Part.Wire(S1.Edges) P = W.extrude(Base.Vector(0, 0, 10))

Show it all

Part.show(P)

Create basic shapes

You can easily create basic topological objects with the make...() methods from the Part module: b = Part.makeBox(100, 100, 100) Part.show(b) Some available make...() methods: makeBox(l, w, h, [p, d]) Makes a box located in p and pointing into the direction d with the dimensions (l,w,h). makeCircle(radius) Makes a circle with a given radius. makeCone(radius1, radius2, height) Makes a cone with the given radii and height. makeCylinder(radius, height) Makes a cylinder with a given radius and height. makeLine((x1, y1, z1), (x2, y2, z2)) Makes a line from two points. makePlane(length, width) Makes a plane with length and width. makePolygon(list) Makes a polygon from a list of points. makeSphere(radius) Makes a sphere with a given radius. makeTorus(radius1, radius2) Makes a torus with the given radii. See the Part API page for a complete list of available methods of the Part module.

Import modules

First we need to import the Part module so we can use its contents in Python. We'll also import the Base module from inside the FreeCAD module: import Part from FreeCAD import Base

Create a vector

Vectors are one of the most important pieces of information when building shapes. They usually contain three numbers (but not necessarily always): the X, Y and Z cartesian coordinates. You create a vector like this: myVector = Base.Vector(3, 2, 0) We just created a vector at coordinates X = 3, Y = 2, Z = 0. In the Part module, vectors are used everywhere. Part shapes also use another kind of point representation called Vertex which is simply a container for a vector. You access the vector of a vertex like this: myVertex = myShape.Vertexes[0] print(myVertex.Point) > Vector (3, 2, 0)

Create an edge

An edge is nothing but a line with two vertices: edge = Part.makeLine((0, 0, 0), (10, 0, 0)) edge.Vertexes > [<Vertex object at 01877430>, <Vertex object at 014888E0>] Note: You can also create an edge by passing two vectors: vec1 = Base.Vector(0, 0, 0) vec2 = Base.Vector(10, 0, 0) line = Part.LineSegment(vec1, vec2) edge = line.toShape() You can find the length and center of an edge like this: edge.Length > 10.0 edge.CenterOfMass > Vector (5, 0, 0)

Put the shape on screen

So far we created an edge object, but it doesn't appear anywhere on the screen. This is because the FreeCAD 3D scene only displays what you tell it to display. To do that, we use this simple method: Part.show(edge) The show function creates an object in our FreeCAD document and assigns our "edge" shape to it. Use this whenever it is time to display your creation on screen.

Create a wire

A wire is a multi-edge line and can be created from a list of edges or even a list of wires: edge1 = Part.makeLine((0, 0, 0), (10, 0, 0)) edge2 = Part.makeLine((10, 0, 0), (10, 10, 0)) wire1 = Part.Wire([edge1, edge2]) edge3 = Part.makeLine((10, 10, 0), (0, 10, 0)) edge4 = Part.makeLine((0, 10, 0), (0, 0, 0)) wire2 = Part.Wire([edge3, edge4]) wire3 = Part.Wire([wire1, wire2]) wire3.Edges > [<Edge object at 016695F8>, <Edge object at 0197AED8>, <Edge object at 01828B20>, <Edge object at 0190A788>] Part.show(wire3) Part.show(wire3) will display the 4 edges that compose our wire. Other useful information can be easily retrieved: wire3.Length > 40.0 wire3.CenterOfMass > Vector (5, 5, 0) wire3.isClosed() > True wire2.isClosed() > False

Create a face

Only faces created from closed wires will be valid. In this example, wire3 is a closed wire but wire2 is not (see above): face = Part.Face(wire3) face.Area > 99.99999999999999 face.CenterOfMass > Vector (5, 5, 0) face.Length > 40.0 face.isValid() > True sface = Part.Face(wire2) sface.isValid() > False Only faces will have an area, wires and edges do not.

Create a circle

A circle can be created like this: circle = Part.makeCircle(10) circle.Curve > Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1)) If you want to create it at a certain position and with a certain direction: ccircle = Part.makeCircle(10, Base.Vector(10, 0, 0), Base.Vector(1, 0, 0)) ccircle.Curve > Circle (Radius : 10, Position : (10, 0, 0), Direction : (1, 0, 0)) ccircle will be created at distance 10 from the X origin and will be facing outwards along the X axis. Note: makeCircle() only accepts Base.Vector() for the position and normal parameters, not tuples. You can also create part of the circle by giving a start and an end angle: from math import pi arc1 = Part.makeCircle(10, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 180) arc2 = Part.makeCircle(10, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 180, 360) Angles should be provided in degrees. If you have radians simply convert them using the formula: degrees = radians * 180/pi or by using Python's math module: import math degrees = math.degrees(radians)

Create an arc along points

Unfortunately there is no makeArc() function, but we have the Part.Arc() function to create an arc through three points. It creates an arc object joining the start point to the end point through the middle point. The arc object's toShape() function must be called to get an edge object, the same as when using Part.LineSegment instead of Part.makeLine. arc = Part.Arc(Base.Vector(0, 0, 0), Base.Vector(0, 5, 0), Base.Vector(5, 5, 0)) arc > <Arc object> arc_edge = arc.toShape() Part.show(arc_edge) Arc() only accepts Base.Vector() for points and not tuples. You can also obtain an arc by using a portion of a circle: from math import pi circle = Part.Circle(Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 10) arc = Part.Arc(circle,0,pi) Arcs are valid edges like lines, so they can be used in wires also.

Create a polygon

A polygon is simply a wire with multiple straight edges. The makePolygon() function takes a list of points and creates a wire through those points: lshape_wire = Part.makePolygon([Base.Vector(0, 5, 0), Base.Vector(0, 0, 0), Base.Vector(5, 0, 0)])

Create a bézier curve

Bézier curves are used to model smooth curves using a series of poles (points) and optional weights. The function below makes a Part.BezierCurve() from a series of FreeCAD.Vector() points. Note: when "getting" and "setting" a single pole or weight, indices start at 1, not 0. def makeBCurveEdge(Points): geomCurve = Part.BezierCurve() geomCurve.setPoles(Points) edge = Part.Edge(geomCurve) return(edge)

Create a plane

A Plane is a flat rectangular surface. The method used to create one is makePlane(length, width, [start_pnt, dir_normal]). By default start_pnt = Vector(0, 0, 0) and dir_normal = Vector(0, 0, 1). Using dir_normal = Vector(0, 0, 1) will create the plane facing in the positive Z axis direction, while dir_normal = Vector(1, 0, 0) will create the plane facing in the positive X axis direction: plane = Part.makePlane(2, 2) plane > <Face object at 028AF990> plane = Part.makePlane(2, 2, Base.Vector(3, 0, 0), Base.Vector(0, 1, 0)) plane.BoundBox > BoundBox (3, 0, 0, 5, 0, 2) BoundBox is a cuboid enclosing the plane with a diagonal starting at (3, 0, 0) and ending at (5, 0, 2). Here the BoundBox thickness along the Y axis is zero, since our shape is totally flat. Note: makePlane() only accepts Base.Vector() for start_pnt and dir_normal and not tuples.

Create an ellipse

There are several ways to create an ellipse: Part.Ellipse() Creates an ellipse with major radius 2 and minor radius 1 with the center at (0, 0, 0). Part.Ellipse(Ellipse) Creates a copy of the given ellipse. Part.Ellipse(S1, S2, Center) Creates an ellipse centered on the point Center, where the plane of the ellipse is defined by Center, S1 and S2, its major axis is defined by Center and S1, its major radius is the distance between Center and S1, and its minor radius is the distance between S2 and the major axis. Part.Ellipse(Center, MajorRadius, MinorRadius) Creates an ellipse with major and minor radii MajorRadius and MinorRadius, located in the plane defined by Center and the normal (0, 0, 1) eli = Part.Ellipse(Base.Vector(10, 0, 0), Base.Vector(0, 5, 0), Base.Vector(0, 0, 0)) Part.show(eli.toShape()) In the above code we have passed S1, S2 and center. Similar to Arc, Ellipse creates an ellipse object not an edge, so we need to convert it into an edge using toShape() for display. Note: Ellipse() only accepts Base.Vector() for points and not tuples. eli = Part.Ellipse(Base.Vector(0, 0, 0), 10, 5) Part.show(eli.toShape()) For the above Ellipse constructor we have passed center, MajorRadius and MinorRadius.

Create a torus

Using makeTorus(radius1, radius2, [pnt, dir, angle1, angle2, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = 0, angle2 = 360 and angle = 360. Consider a torus as small circle sweeping along a big circle. Radius1 is the radius of the big circle, radius2 is the radius of the small circle, pnt is the center of the torus and dir is the normal direction. angle1 and angle2 are angles in degrees for the small circle; the last angle parameter is to make a section of the torus: torus = Part.makeTorus(10, 2) The above code will create a torus with diameter 20 (radius 10) and thickness 4 (small circle radius 2) tor=Part.makeTorus(10, 5, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 180) The above code will create a slice of the torus. tor=Part.makeTorus(10, 5, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 360, 180) The above code will create a semi torus; only the last parameter is changed. i.e the remaining angles are defaults. Giving the angle 180 will create the torus from 0 to 180, that is, a half torus.

Create a box or cuboid

Using makeBox(length, width, height, [pnt, dir]). By default pnt = Vector(0, 0, 0) and dir = Vector(0, 0, 1). box = Part.makeBox(10, 10, 10) len(box.Vertexes) > 8

Create a sphere

Using makeSphere(radius, [pnt, dir, angle1, angle2, angle3]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = -90, angle2 = 90 and angle3 = 360. Angle1 and angle2 are the vertical minimum and maximum of the sphere, angle3 is the sphere diameter. sphere = Part.makeSphere(10) hemisphere = Part.makeSphere(10, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), -90, 90, 180)

Create a cylinder

Using makeCylinder(radius, height, [pnt, dir, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360. cylinder = Part.makeCylinder(5, 20) partCylinder = Part.makeCylinder(5, 20, Base.Vector(20, 0, 0), Base.Vector(0, 0, 1), 180)

Create a cone

Using makeCone(radius1, radius2, height, [pnt, dir, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360. cone = Part.makeCone(10, 0, 20) semicone = Part.makeCone(10, 0, 20, Base.Vector(20, 0, 0), Base.Vector(0, 0, 1), 180)

Modify shapes

There are several ways to modify shapes. Some are simple transformation operations such as moving or rotating shapes, others are more complex, such as unioning and subtracting one shape from another.

Transform operations

Translate a shape

Translating is the act of moving a shape from one place to another. Any shape (edge, face, cube, etc...) can be translated the same way: myShape = Part.makeBox(2, 2, 2) myShape.translate(Base.Vector(2, 0, 0)) This will move our shape "myShape" 2 units in the X direction.

Rotate a shape

To rotate a shape, you need to specify the rotation center, the axis, and the rotation angle: myShape.rotate(Base.Vector(0, 0, 0),Base.Vector(0, 0, 1), 180) The above code will rotate the shape 180 degrees around the Z Axis.

Matrix transformations

A matrix is a very convenient way to store transformations in the 3D world. In a single matrix, you can set translation, rotation and scaling values to be applied to an object. For example: myMat = Base.Matrix() myMat.move(Base.Vector(2, 0, 0)) myMat.rotateZ(math.pi/2) Note: FreeCAD matrixes work in radians. Also, almost all matrix operations that take a vector can also take three numbers, so these two lines do the same thing: myMat.move(2, 0, 0) myMat.move(Base.Vector(2, 0, 0)) Once our matrix is set, we can apply it to our shape. FreeCAD provides two methods for doing that: transformShape() and transformGeometry(). The difference is that with the first one, you are sure that no deformations will occur (see Scaling a shape below). We can apply our transformation like this: myShape.transformShape(myMat) or myShape.transformGeometry(myMat)

Scale a shape

Scaling a shape is a more dangerous operation because, unlike translation or rotation, scaling non-uniformly (with different values for X, Y and Z) can modify the structure of the shape. For example, scaling a circle with a higher value horizontally than vertically will transform it into an ellipse, which behaves mathematically very differently. For scaling, we cannot use the transformShape(), we must use transformGeometry(): myMat = Base.Matrix() myMat.scale(2, 1, 1) myShape=myShape.transformGeometry(myMat)

Boolean operations

Subtraction

Subtracting a shape from another one is called "cut" in FreeCAD and is done like this: cylinder = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0)) sphere = Part.makeSphere(5, Base.Vector(5, 0, 0)) diff = cylinder.cut(sphere)

Intersection

The same way, the intersection between two shapes is called "common" and is done this way: cylinder1 = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0)) cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1)) common = cylinder1.common(cylinder2)

Union

Union is called "fuse" and works the same way: cylinder1 = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0)) cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1)) fuse = cylinder1.fuse(cylinder2)

Section

A "section" is the intersection between a solid shape and a plane shape. It will return an intersection curve, a compound curve composed of edges. cylinder1 = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0)) cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1)) section = cylinder1.section(cylinder2) section.Wires > [] section.Edges > [<Edge object at 0D87CFE8>, <Edge object at 019564F8>, <Edge object at 0D998458>, <Edge object at 0D86DE18>, <Edge object at 0D9B8E80>, <Edge object at 012A3640>, <Edge object at 0D8F4BB0>]

Extrusion

Extrusion is the act of "pushing" a flat shape in a certain direction, resulting in a solid body. Think of a circle becoming a tube by "pushing it out": circle = Part.makeCircle(10) tube = circle.extrude(Base.Vector(0, 0, 2)) If your circle is hollow, you will obtain a hollow tube. If your circle is actually a disc with a filled face, you will obtain a solid cylinder: wire = Part.Wire(circle) disc = Part.Face(wire) cylinder = disc.extrude(Base.Vector(0, 0, 2))

Explore shapes

You can easily explore the topological data structure: import Part b = Part.makeBox(100, 100, 100) b.Wires w = b.Wires[0] w w.Wires w.Vertexes Part.show(w) w.Edges e = w.Edges[0] e.Vertexes v = e.Vertexes[0] v.Point By typing the lines above in the Python interpreter, you will gain a good understanding of the structure of Part objects. Here, our makeBox() command created a solid shape. This solid, like all Part solids, contains faces. Faces always contain wires, which are lists of edges that border the face. Each face has at least one closed wire (it can have more if the face has a hole). In the wire, we can look at each edge separately, and inside each edge, we can see the vertices. Straight edges have only two vertices, obviously.

Edge analysis

In case of an edge, which is an arbitrary curve, it's most likely you want to do a discretization. In FreeCAD the edges are parametrized by their lengths. That means you can walk an edge/curve by its length: import Part box = Part.makeBox(100, 100, 100) anEdge = box.Edges[0] print(anEdge.Length) Now you can access a lot of properties of the edge by using the length as a position. That means if the edge is 100mm long the start position is 0 and the end position 100. anEdge.tangentAt(0.0) # tangent direction at the beginning anEdge.valueAt(0.0) # Point at the beginning anEdge.valueAt(100.0) # Point at the end of the edge anEdge.derivative1At(50.0) # first derivative of the curve in the middle anEdge.derivative2At(50.0) # second derivative of the curve in the middle anEdge.derivative3At(50.0) # third derivative of the curve in the middle anEdge.centerOfCurvatureAt(50) # center of the curvature for that position anEdge.curvatureAt(50.0) # the curvature anEdge.normalAt(50) # normal vector at that position (if defined)

Use a selection

Here we see now how we can use a selection the user did in the viewer. First of all we create a box and show it in the viewer. import Part Part.show(Part.makeBox(100, 100, 100)) Gui.SendMsgToActiveView("ViewFit") Now select some faces or edges. With this script you can iterate over all selected objects and their sub elements: for o in Gui.Selection.getSelectionEx(): print(o.ObjectName) for s in o.SubElementNames: print("name: ", s) for s in o.SubObjects: print("object: ", s) Select some edges and this script will calculate the length: length = 0.0 for o in Gui.Selection.getSelectionEx(): for s in o.SubObjects: length += s.Length print("Length of the selected edges: ", length)

Example: The OCC bottle

A typical example found on the OpenCasCade Technology website is how to build a bottle. This is a good exercise for FreeCAD too. In fact, if you follow our example below and the OCC page simultaneously, you will see how well OCC structures are implemented in FreeCAD. The script is included in the FreeCAD installation (inside the Mod/Part folder) and can be called from the Python interpreter by typing: import Part import MakeBottle bottle = MakeBottle.makeBottle() Part.show(bottle)

The script

For the purpose of this tutorial we will consider a reduced version of the script. In this version the bottle will not be hollowed out, and the neck of the bottle will not be threaded. import Part, math from FreeCAD import Base def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0): aPnt1=Base.Vector(-myWidth / 2., 0, 0) aPnt2=Base.Vector(-myWidth / 2., -myThickness / 4., 0) aPnt3=Base.Vector(0, -myThickness / 2., 0) aPnt4=Base.Vector(myWidth / 2., -myThickness / 4., 0) aPnt5=Base.Vector(myWidth / 2., 0, 0) aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4) aSegment1=Part.LineSegment(aPnt1, aPnt2) aSegment2=Part.LineSegment(aPnt4, aPnt5) aEdge1=aSegment1.toShape() aEdge2=aArcOfCircle.toShape() aEdge3=aSegment2.toShape() aWire=Part.Wire([aEdge1, aEdge2, aEdge3]) aTrsf=Base.Matrix() aTrsf.rotateZ(math.pi) # rotate around the z-axis aMirroredWire=aWire.copy() aMirroredWire.transformShape(aTrsf) myWireProfile=Part.Wire([aWire, aMirroredWire]) myFaceProfile=Part.Face(myWireProfile) aPrismVec=Base.Vector(0, 0, myHeight) myBody=myFaceProfile.extrude(aPrismVec) myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges) neckLocation=Base.Vector(0, 0, myHeight) neckNormal=Base.Vector(0, 0, 1) myNeckRadius = myThickness / 4. myNeckHeight = myHeight / 10. myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal) myBody = myBody.fuse(myNeck) return myBody el = makeBottleTut() Part.show(el)

Detailed explanation

import Part, math from FreeCAD import Base We will need, of course, the Part module, but also the FreeCAD.Base module, which contains basic FreeCAD structures like vectors and matrices. def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0): aPnt1=Base.Vector(-myWidth / 2., 0, 0) aPnt2=Base.Vector(-myWidth / 2., -myThickness / 4., 0) aPnt3=Base.Vector(0, -myThickness / 2., 0) aPnt4=Base.Vector(myWidth / 2., -myThickness / 4., 0) aPnt5=Base.Vector(myWidth / 2., 0, 0) Here we define our makeBottleTut function. This function can be called without arguments, like we did above, in which case default values for width, height, and thickness will be used. Then, we define a couple of points that will be used for building our base profile. ... aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4) aSegment1=Part.LineSegment(aPnt1, aPnt2) aSegment2=Part.LineSegment(aPnt4, aPnt5) Here we define the geometry: an arc, made of three points, and two line segments, made of two points. ... aEdge1=aSegment1.toShape() aEdge2=aArcOfCircle.toShape() aEdge3=aSegment2.toShape() aWire=Part.Wire([aEdge1, aEdge2, aEdge3]) Remember the difference between geometry and shapes? Here we build shapes out of our construction geometry. Three edges (edges can be straight or curved), then a wire made of those three edges. ... aTrsf=Base.Matrix() aTrsf.rotateZ(math.pi) # rotate around the z-axis aMirroredWire=aWire.copy() aMirroredWire.transformShape(aTrsf) myWireProfile=Part.Wire([aWire, aMirroredWire]) So far we have built only a half profile. Instead of building the whole profile the same way, we can just mirror what we did and glue both halves together. We first create a matrix. A matrix is a very common way to apply transformations to objects in the 3D world, since it can contain in one structure all basic transformations that 3D objects can undergo (move, rotate and scale). After we create the matrix we mirror it, then we create a copy of our wire and apply the transformation matrix to it. We now have two wires, and we can make a third wire out of them, since wires are actually lists of edges. ... myFaceProfile=Part.Face(myWireProfile) aPrismVec=Base.Vector(0, 0, myHeight) myBody=myFaceProfile.extrude(aPrismVec) myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges) Now that we have a closed wire, it can be turned into a face. Once we have a face, we can extrude it. In doing so, we make a solid. Then we apply a nice little fillet to our object because we care about good design, don't we? ... neckLocation=Base.Vector(0, 0, myHeight) neckNormal=Base.Vector(0, 0, 1) myNeckRadius = myThickness / 4. myNeckHeight = myHeight / 10. myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal) At this point, the body of our bottle is made, but we still need to create a neck. So we make a new solid, with a cylinder. ... myBody = myBody.fuse(myNeck) The fuse operation is very powerful. It will take care of gluing what needs to be glued and remove parts that need to be removed. ... return myBody Then, we return our Part solid as the result of our function. el = makeBottleTut() Part.show(el) Finally, we call the function to actually create the part, then make it visible.

Example: Pierced box

Here is a complete example of building a pierced box. The construction is done one side at a time. When the cube is finished, it is hollowed out by cutting a cylinder through it. import Part, math from FreeCAD import Base size = 10 poly = Part.makePolygon([(0, 0, 0), (size, 0, 0), (size, 0, size), (0, 0, size), (0, 0, 0)]) face1 = Part.Face(poly) face2 = Part.Face(poly) face3 = Part.Face(poly) face4 = Part.Face(poly) face5 = Part.Face(poly) face6 = Part.Face(poly) myMat = Base.Matrix() myMat.rotateZ(math.pi / 2) face2.transformShape(myMat) face2.translate(Base.Vector(size, 0, 0)) myMat.rotateZ(math.pi / 2) face3.transformShape(myMat) face3.translate(Base.Vector(size, size, 0)) myMat.rotateZ(math.pi / 2) face4.transformShape(myMat) face4.translate(Base.Vector(0, size, 0)) myMat = Base.Matrix() myMat.rotateX(-math.pi / 2) face5.transformShape(myMat) face6.transformShape(myMat) face6.translate(Base.Vector(0, 0, size)) myShell = Part.makeShell([face1, face2, face3, face4, face5, face6]) mySolid = Part.makeSolid(myShell) myCyl = Part.makeCylinder(2, 20) myCyl.translate(Base.Vector(size / 2, size / 2, 0)) cut_part = mySolid.cut(myCyl) Part.show(cut_part)

Loading and saving

There are several ways to save your work. You can of course save your FreeCAD document, but you can also save Part objects directly to common CAD formats, such as BREP, IGS, STEP and STL. Saving a shape to a file is easy. There are exportBrep(), exportIges(), exportStep() and exportStl() methods available for all shape objects. So, doing: import Part s = Part.makeBox(10, 10, 10) s.exportStep("test.stp") will save our box into a STEP file. To load a BREP, IGES or STEP file: import Part s = Part.Shape() s.read("test.stp") To convert a STEP file to an IGS file: import Part s = Part.Shape() s.read("file.stp") # incoming file igs, stp, stl, brep s.exportIges("file.igs") # outbound file igs


Scenegraph

Introduction

The geometry that appears in the 3D views of FreeCAD is rendered by the Coin3D library. Coin3D is an implementation of the OpenInventor standard. The OpenCASCADE software also provides the same functionality, but it was decided at the very early stages of FreeCAD not to use the built-in OpenCASCADE viewer, but rather switch to the more performant Coin3D software. A good way to learn about that library is the book Open Inventor Mentor.

Description

OpenInventor is a 3D scene description language. The scene described in OpenInventor is then rendered in OpenGL on your screen. Coin3D takes care of doing this, so programmers do not need to deal with complex OpenGL calls, and may just provide valid OpenInventor code. The big advantage is that OpenInventor is a very well-known and well documented standard. One of the big jobs FreeCAD does for you is translating OpenCASCADE geometry information into OpenInventor language. OpenInventor describes a 3D scene in the form of a scenegraph, like the one below: Image taken from Inventor mentor An openInventor scenegraph describes everything that is part of a 3D scene, such as geometry, colors, materials, lights, etc, and organizes all that data in a convenient and clear structure. Everything can be grouped into sub-structures, allowing you to organize your scene contents pretty much the way you like. Here is an example of an openInventor file: #Inventor V2.0 ascii Separator { RotationXYZ { axis Z angle 0 } Transform { translation 0 0 0.5 } Separator { Material { diffuseColor 0.05 0.05 0.05 } Transform { rotation 1 0 0 1.5708 scaleFactor 0.2 0.5 0.2 } Cylinder { } } } As you can see, the structure is very simple. You use separators to organize your data into blocks, a bit like you would organize your files into folders. Each statement affects what comes next, for example the first two items of our root separator are a rotation and a translation, both will affect the next item, which is a separator. In that separator a material is defined and another transformation. Our cylinder will therefore be affected by both transformations, the one applied directly to it and the one that was applied to its parent separator. We also have many other types of elements to organize our scene, such as groups, switches or annotations. We can define very complex materials for our objects, with colors, textures, shading modes and transparency. We can also define lights, cameras, and even movement. It is even possible to embed pieces of scripting in openInventor files to define more complex behaviors. If you are interested in learning more about openInventor head directly to its most famous reference: the Inventor mentor. In FreeCAD, normally, we don't need to interact directly with the openInventor scenegraph. Every object in a FreeCAD document, being a mesh, a part shape or anything else, gets automatically converted to openInventor code and inserted in the main scenegraph that you see in a 3D view. That scenegraph gets updated continuously when you modify, add or remove objects. In fact every object (in App space) has a view provider (a corresponding object in Gui space) responsible for issuing openInventor code. But there are many advantages to being able to access the scenegraph directly. For example, we can temporarily change the appearance of an object, or we can add objects to the scene that have no real existence in the FreeCAD document, such as construction geometry, helpers, graphical hints or tools such as manipulators or on-screen information. FreeCAD itself features several tools to see or modify openInventor code. For example, the following python code will show the openInventor representation of a selected object: obj = FreeCAD.ActiveDocument.ActiveObject viewprovider = obj.ViewObject print viewprovider.toString() But we also have a python module that allows complete access to anything managed by Coin3D, such as our FreeCAD scenegraph. So, read on to Pivy.

Coding examples

See Coin3d snippets courtesy of MariwanJ's research for the Design456 Workbench. The code repository of said examples can be found at https://github.com/MariwanJ/COIN3D_Examples.


PySide

Introduction

The PySide library gives access to the cross-platform graphical user interface (GUI) toolkit Qt from Python. Qt is a collection of C++ libraries, but with the help of PySide, the same components can be used from Python. Every graphical interface that can be created in C++, can also be created and modified in Python. An advantage of using Python is that Qt interfaces can be developed and tested live, as we don't need to compile the source files. When you install FreeCAD, you should get both Qt and PySide as part of the package. If you are compiling yourself then you must verify that these two libraries are installed in order for FreeCAD to run correctly. Of course, PySide will only work if Qt is present. In the past, FreeCAD used PyQt, another Qt binding for Python, but in 2013 (1dc122dc9a) the project migrated to PySide because it has a more permissible license. For more information see: Wikipedia:PySide Differences Between PySide and PyQt Examples created with PySide. Left: a simple dialog. Right: a more complex dialog with graphs.

PySide in FreeCAD with Qt5

FreeCAD was developed to be used with Python 2 and Qt4. As these two libraries became obsolete, FreeCAD transitioned to Python 3 and Qt5. In most cases this transition was done without needing to break backwards compatibility. Normally, the PySide module provides support for Qt4, while PySide2 provides support for Qt5. However, in FreeCAD there is no need to use PySide2 directly, as a special PySide module is included to handle Qt5. This PySide module is located in the Ext/ directory of an installation of FreeCAD compiled for Qt5. /usr/share/freecad/Ext/PySide This module just imports the necessary classes from PySide2, and places them in the PySide namespace. This means that in most cases the same code can be used with both Qt4 and Qt5, as long as we use the single PySide module. PySide2.QtCore -> PySide.QtCore PySide2.QtGui -> PySide.QtGui PySide2.QtSvg -> PySide.QtSvg PySide2.QtUiTools -> PySide.QtUiTools The only unusual aspect is that the PySide2.QtWidgets classes are placed in the PySide.QtGui namespace. PySide2.QtWidgets.QCheckBox -> PySide.QtGui.QCheckBox ]

Examples of PySide use

PySide Beginner Examples, hello world, announcements, enter text, enter number. PySide Intermediate Examples, window sizing, hiding widgets, popup menus, mouse position, mouse events. PySide Advanced Examples, many widgets. The examples of PySide are divided into 3 parts, differentiated by level of exposure to PySide, Python and the FreeCAD internals. The first page has an overview on PySide; the second and third pages are mostly code examples at different levels. It is expected that these examples are useful to get started, and afterwards the user can consult other resources online, or the official documentation.

Documentation

There are some differences in handling of widgets in Qt4 (PySide) and Qt5 (PySide2). The programmer should be aware of these incompatibilities, and should consult the official documentation if something doesn't seem to work as expected on a given platform. Nevertheless, Qt4 is considered obsolete, so most development should target Qt5 and Python 3. The PySide documentation refers to the Python-style classes; however, since Qt is originally a C++ library, the same information should be available in the corresponding C++ reference. Qt Modules available from PySide2 (Qt5). All Qt classes by module in Qt5 for C++. Qt Modules available from PySide (Qt4).


Scripted objects

Introduction

Besides the standard object types such as annotations, meshes and parts objects, FreeCAD also offers the amazing possibility to build 100% python-scripted parametric objects, called Python Features. Those objects will behave exactly as any other FreeCAD object, and are saved and restored automatically on file save/load. One particularity must be understood: For security reasons, FreeCAD files never carry any embedded code. The Python code that you write to create parametric objects is never saved inside a file. This means that if you open a file containing such an object on another machine, if that python code is not available on that machine, the object won't be fully recreated. If you distribute such objects to others, you will need to distribute your Python script too, for example as a Macro. Note: It is possible to pack python code inside a FreeCAD file using json serializing with an App::PropertyPythonObject, but that code can never directly be run, and therefore has little use for our purpose here. Python Features follow the same rule as all FreeCAD features: they are separated into App and GUI parts. The app part, the Document Object, defines the geometry of our object, while its GUI part, the View Provider Object, defines how the object will be drawn on screen. The View Provider Object, as any other FreeCAD feature, is only available when you run FreeCAD in its own GUI. There are several properties and methods available to build your object. Properties must be of any of the predefined properties types that FreeCAD offers, and will appear in the property view window, so they can be edited by the user. This way, FeaturePython objects are truly and totally parametric. you can define properties for the Object and its ViewObject separately.

Basic example

The following sample can be found in the src/Mod/TemplatePyMod/FeaturePython.py file, together with several other examples: '''Examples for a feature class and its view provider.''' import FreeCAD, FreeCADGui from pivy import coin class Box: def __init__(self, obj): '''Add some custom properties to our box feature''' obj.addProperty("App::PropertyLength","Length","Box","Length of the box").Length=1.0 obj.addProperty("App::PropertyLength","Width","Box","Width of the box").Width=1.0 obj.addProperty("App::PropertyLength","Height","Box", "Height of the box").Height=1.0 obj.Proxy = self def onChanged(self, fp, prop): '''Do something when a property has changed''' FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n") def execute(self, fp): '''Do something when doing a recomputation, this method is mandatory''' FreeCAD.Console.PrintMessage("Recompute Python Box feature\n") class ViewProviderBox: def __init__(self, obj): '''Set this object to the proxy object of the actual view provider''' obj.addProperty("App::PropertyColor","Color","Box","Color of the box").Color=(1.0,0.0,0.0) obj.Proxy = self def attach(self, obj): '''Setup the scene sub-graph of the view provider, this method is mandatory''' self.shaded = coin.SoGroup() self.wireframe = coin.SoGroup() self.scale = coin.SoScale() self.color = coin.SoBaseColor() data=coin.SoCube() self.shaded.addChild(self.scale) self.shaded.addChild(self.color) self.shaded.addChild(data) obj.addDisplayMode(self.shaded,"Shaded"); style=coin.SoDrawStyle() style.style = coin.SoDrawStyle.LINES self.wireframe.addChild(style) self.wireframe.addChild(self.scale) self.wireframe.addChild(self.color) self.wireframe.addChild(data) obj.addDisplayMode(self.wireframe,"Wireframe"); self.onChanged(obj,"Color") def updateData(self, fp, prop): '''If a property of the handled feature has changed we have the chance to handle this here''' # fp is the handled feature, prop is the name of the property that has changed l = fp.getPropertyByName("Length") w = fp.getPropertyByName("Width") h = fp.getPropertyByName("Height") self.scale.scaleFactor.setValue(float(l),float(w),float(h)) pass def getDisplayModes(self,obj): '''Return a list of display modes.''' modes=[] modes.append("Shaded") modes.append("Wireframe") return modes def getDefaultDisplayMode(self): '''Return the name of the default display mode. It must be defined in getDisplayModes.''' return "Shaded" def setDisplayMode(self,mode): '''Map the display mode defined in attach with those defined in getDisplayModes.\ Since they have the same names nothing needs to be done. This method is optional''' return mode def onChanged(self, vp, prop): '''Here we can do something when a single property got changed''' FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n") if prop == "Color": c = vp.getPropertyByName("Color") self.color.rgb.setValue(c[0],c[1],c[2]) def getIcon(self): '''Return the icon in XPM format which will appear in the tree view. This method is\ optional and if not defined a default icon is shown.''' return """ /* XPM */ static const char * ViewProviderBox_xpm[] = { "16 16 6 1", " c None", ". c #141010", "+ c #615BD2", "@ c #C39D55", "# c #000000", "$ c #57C355", " ........", " ......++..+..", " .@@@@.++..++.", " .@@@@.++..++.", " .@@ .++++++.", " ..@@ .++..++.", "###@@@@ .++..++.", "##$.@@$#.++++++.", "#$#$.$$$........", "#$$####### ", "#$$#$$$$$# ", "#$$#$$$$$# ", "#$$#$$$$$# ", " #$#$$$$$# ", " ##$$$$$# ", " ####### "}; """ def __getstate__(self): '''When saving the document this object gets stored using Python's json module.\ Since we have some un-serializable parts here -- the Coin stuff -- we must define this method\ to return a tuple of all serializable objects or None.''' return None def __setstate__(self,state): '''When restoring the serialized object from document we have the chance to set some internals here.\ Since no data were serialized nothing needs to be done here.''' return None def makeBox(): FreeCAD.newDocument() a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Box") Box(a) ViewProviderBox(a.ViewObject) makeBox()

Things to note

If your object relies on being recomputed as soon as it is created, you must do this manually in the __init__ function as it is not called automatically. This example does not require it because the onChanged method of the Box class has the same effect as the execute function, but the examples below rely on being recomputed before anything is displayed in the 3D view. In the examples, this is done manually with ActiveDocument.recompute() but in more complex scenarios you need to decide where to recompute either the whole document or the FeaturePython object. This example produces a number of exception stack traces in the report view window. This is because the onChanged method of the Box class is called each time a property is added in __init__. When the first one is added, the Width and Height properties don't exist yet and so the attempt to access them fails. An explanation of __getstate__ and __setstate__ is in the forum thread obj.Proxy.Type is a dict, not a string.

Available methods

See FeaturePython methods for the complete reference.

Available properties

Properties are the true building stones of FeaturePython objects. Through them, the user will be able to interact and modify your object. After creating a new FeaturePython object in your document ( obj=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Box") ), you can get a list of the available properties by issuing: obj.supportedProperties() You will get a list of available properties, which are described more in depth on the FeaturePython Custom Properties page: App::PropertyAcceleration App::PropertyAngle App::PropertyArea App::PropertyBool App::PropertyBoolList App::PropertyColor App::PropertyColorList App::PropertyDirection App::PropertyDistance App::PropertyEnumeration App::PropertyExpressionEngine App::PropertyFile App::PropertyFileIncluded App::PropertyFloat App::PropertyFloatConstraint App::PropertyFloatList App::PropertyFont App::PropertyForce App::PropertyFrequency App::PropertyInteger App::PropertyIntegerConstraint App::PropertyIntegerList App::PropertyIntegerSet App::PropertyLength App::PropertyLink App::PropertyLinkChild App::PropertyLinkGlobal App::PropertyLinkHidden App::PropertyLinkList App::PropertyLinkListChild App::PropertyLinkListGlobal App::PropertyLinkListHidden App::PropertyLinkSub App::PropertyLinkSubChild App::PropertyLinkSubGlobal App::PropertyLinkSubHidden App::PropertyLinkSubList App::PropertyLinkSubListChild App::PropertyLinkSubListGlobal App::PropertyLinkSubListHidden App::PropertyMap App::PropertyMaterial App::PropertyMaterialList App::PropertyMatrix App::PropertyPath App::PropertyPercent App::PropertyPersistentObject App::PropertyPlacement App::PropertyPlacementLink App::PropertyPlacementList App::PropertyPosition App::PropertyPrecision App::PropertyPressure App::PropertyPythonObject App::PropertyQuantity App::PropertyQuantityConstraint App::PropertySpeed App::PropertyString App::PropertyStringList App::PropertyUUID App::PropertyVacuumPermittivity App::PropertyVector App::PropertyVectorDistance App::PropertyVectorList App::PropertyVolume App::PropertyXLink App::PropertyXLinkList App::PropertyXLinkSub App::PropertyXLinkSubList Mesh::PropertyCurvatureList Mesh::PropertyMeshKernel Mesh::PropertyNormalList Part::PropertyFilletEdges Part::PropertyGeometryList Part::PropertyPartShape Part::PropertyShapeHistory Path::PropertyPath Path::PropertyTool Path::PropertyTooltable Sketcher::PropertyConstraintList Spreadsheet::PropertyColumnWidths Spreadsheet::PropertyRowHeights Spreadsheet::PropertySheet Spreadsheet::PropertySpreadsheetQuantity TechDraw::PropertyCenterLineList TechDraw::PropertyCosmeticEdgeList TechDraw::PropertyCosmeticVertexList TechDraw::PropertyGeomFormatList When adding properties to your custom objects, take care of this: Do not use characters "<" or ">" in the properties descriptions (that would break the xml pieces in the .fcstd file) Properties are stored alphabetically in a .fcstd file. If you have a shape in your properties, any property whose name comes after "Shape" in alphabetic order, will be loaded AFTER the shape, which can cause strange behaviours. A complete list of property attributes can be seen in the PropertyStandard C++ header file. For instance, if you want to allow the user to enter only a limited range of values (e.g. using PropertyIntegerConstraint), in Python you will assign a tuple containing not only the property value, but also the lower and upper limit as well as the stepsize, as below: prop = (value, lower, upper, stepsize)

Property Type

By default the properties can be updated. It is possible to make the properties read-only, for instance in the case one wants to show the result of a method. It is also possible to hide the property. The property type can be set using: obj.setEditorMode("MyPropertyName", mode) where mode is a short int that can be set to: 0 -- default mode, read and write 1 -- read-only 2 -- hidden The EditorModes are not set at FreeCAD file reload. This could to be done by the __setstate__ function. See http://forum.freecadweb.org/viewtopic.php?f=18&t=13460&start=10#p108072. By using the setEditorMode the properties are only read only in PropertyEditor. They could still be changed from python. To really make them read only the setting has to be passed directly inside the addProperty function. See http://forum.freecadweb.org/viewtopic.php?f=18&t=13460&start=20#p109709 for an example. Using the direct setting in the addProperty function, you also have more possibilities. In particular, an interesting one is mark a property as an output property. This way FreeCAD won't mark the feature as touched when changing it (so no need to recompute). Example of output property (see also https://forum.freecadweb.org/viewtopic.php?t=24928): obj.addProperty("App::PropertyString","MyCustomProperty","","",8) The property types that can be set at last parameter of the addProperty function are: 0 -- Prop_None, No special property type 1 -- Prop_ReadOnly, Property is read-only in the editor 2 -- Prop_Transient, Property won't be saved to file 4 -- Prop_Hidden, Property won't appear in the editor 8 -- Prop_Output, Modified property doesn't touch its parent container 16 -- Prop_NoRecompute, Modified property doesn't touch its container for recompute You can find these different property types defined in the source code C++ header for PropertyContainer.

Other more complex example

This example makes use of the Part module to create an octahedron, then creates its coin representation with pivy. First is the Document object itself: import FreeCAD, FreeCADGui, Part import pivy from pivy import coin class Octahedron: def __init__(self, obj): "Add some custom properties to our box feature" obj.addProperty("App::PropertyLength","Length","Octahedron","Length of the octahedron").Length=1.0 obj.addProperty("App::PropertyLength","Width","Octahedron","Width of the octahedron").Width=1.0 obj.addProperty("App::PropertyLength","Height","Octahedron", "Height of the octahedron").Height=1.0 obj.addProperty("Part::PropertyPartShape","Shape","Octahedron", "Shape of the octahedron") obj.Proxy = self def execute(self, fp): # Define six vetices for the shape v1 = FreeCAD.Vector(0,0,0) v2 = FreeCAD.Vector(fp.Length,0,0) v3 = FreeCAD.Vector(0,fp.Width,0) v4 = FreeCAD.Vector(fp.Length,fp.Width,0) v5 = FreeCAD.Vector(fp.Length/2,fp.Width/2,fp.Height/2) v6 = FreeCAD.Vector(fp.Length/2,fp.Width/2,-fp.Height/2) # Make the wires/faces f1 = self.make_face(v1,v2,v5) f2 = self.make_face(v2,v4,v5) f3 = self.make_face(v4,v3,v5) f4 = self.make_face(v3,v1,v5) f5 = self.make_face(v2,v1,v6) f6 = self.make_face(v4,v2,v6) f7 = self.make_face(v3,v4,v6) f8 = self.make_face(v1,v3,v6) shell=Part.makeShell([f1,f2,f3,f4,f5,f6,f7,f8]) solid=Part.makeSolid(shell) fp.Shape = solid # helper mehod to create the faces def make_face(self,v1,v2,v3): wire = Part.makePolygon([v1,v2,v3,v1]) face = Part.Face(wire) return face Then, we have the view provider object, responsible for showing the object in the 3D scene: class ViewProviderOctahedron: def __init__(self, obj): "Set this object to the proxy object of the actual view provider" obj.addProperty("App::PropertyColor","Color","Octahedron","Color of the octahedron").Color=(1.0,0.0,0.0) obj.Proxy = self def attach(self, obj): "Setup the scene sub-graph of the view provider, this method is mandatory" self.shaded = coin.SoGroup() self.wireframe = coin.SoGroup() self.scale = coin.SoScale() self.color = coin.SoBaseColor() self.data=coin.SoCoordinate3() self.face=coin.SoIndexedLineSet() self.shaded.addChild(self.scale) self.shaded.addChild(self.color) self.shaded.addChild(self.data) self.shaded.addChild(self.face) obj.addDisplayMode(self.shaded,"Shaded"); style=coin.SoDrawStyle() style.style = coin.SoDrawStyle.LINES self.wireframe.addChild(style) self.wireframe.addChild(self.scale) self.wireframe.addChild(self.color) self.wireframe.addChild(self.data) self.wireframe.addChild(self.face) obj.addDisplayMode(self.wireframe,"Wireframe"); self.onChanged(obj,"Color") def updateData(self, fp, prop): "If a property of the handled feature has changed we have the chance to handle this here" # fp is the handled feature, prop is the name of the property that has changed if prop == "Shape": s = fp.getPropertyByName("Shape") self.data.point.setNum(6) cnt=0 for i in s.Vertexes: self.data.point.set1Value(cnt,i.X,i.Y,i.Z) cnt=cnt+1 self.face.coordIndex.set1Value(0,0) self.face.coordIndex.set1Value(1,1) self.face.coordIndex.set1Value(2,2) self.face.coordIndex.set1Value(3,-1) self.face.coordIndex.set1Value(4,1) self.face.coordIndex.set1Value(5,3) self.face.coordIndex.set1Value(6,2) self.face.coordIndex.set1Value(7,-1) self.face.coordIndex.set1Value(8,3) self.face.coordIndex.set1Value(9,4) self.face.coordIndex.set1Value(10,2) self.face.coordIndex.set1Value(11,-1) self.face.coordIndex.set1Value(12,4) self.face.coordIndex.set1Value(13,0) self.face.coordIndex.set1Value(14,2) self.face.coordIndex.set1Value(15,-1) self.face.coordIndex.set1Value(16,1) self.face.coordIndex.set1Value(17,0) self.face.coordIndex.set1Value(18,5) self.face.coordIndex.set1Value(19,-1) self.face.coordIndex.set1Value(20,3) self.face.coordIndex.set1Value(21,1) self.face.coordIndex.set1Value(22,5) self.face.coordIndex.set1Value(23,-1) self.face.coordIndex.set1Value(24,4) self.face.coordIndex.set1Value(25,3) self.face.coordIndex.set1Value(26,5) self.face.coordIndex.set1Value(27,-1) self.face.coordIndex.set1Value(28,0) self.face.coordIndex.set1Value(29,4) self.face.coordIndex.set1Value(30,5) self.face.coordIndex.set1Value(31,-1) def getDisplayModes(self,obj): "Return a list of display modes." modes=[] modes.append("Shaded") modes.append("Wireframe") return modes def getDefaultDisplayMode(self): "Return the name of the default display mode. It must be defined in getDisplayModes." return "Shaded" def setDisplayMode(self,mode): return mode def onChanged(self, vp, prop): "Here we can do something when a single property got changed" FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n") if prop == "Color": c = vp.getPropertyByName("Color") self.color.rgb.setValue(c[0],c[1],c[2]) def getIcon(self): return """ /* XPM */ static const char * ViewProviderBox_xpm[] = { "16 16 6 1", " c None", ". c #141010", "+ c #615BD2", "@ c #C39D55", "# c #000000", "$ c #57C355", " ........", " ......++..+..", " .@@@@.++..++.", " .@@@@.++..++.", " .@@ .++++++.", " ..@@ .++..++.", "###@@@@ .++..++.", "##$.@@$#.++++++.", "#$#$.$$$........", "#$$####### ", "#$$#$$$$$# ", "#$$#$$$$$# ", "#$$#$$$$$# ", " #$#$$$$$# ", " ##$$$$$# ", " ####### "}; """ def __getstate__(self): return None def __setstate__(self,state): return None Finally, once our object and its viewobject are defined, we just need to call them (The Octahedron class and viewprovider class code could be copied in the FreeCAD python console directly): FreeCAD.newDocument() a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Octahedron") Octahedron(a) ViewProviderOctahedron(a.ViewObject)

Making objects selectable

If you want to make your object selectable, or at least part of it, by clicking on it in the viewport, you must include its coin geometry inside a SoFCSelection node. If your object has complex representation, with widgets, annotations, etc, you might want to include only a part of it in a SoFCSelection. Everything that is a SoFCSelection is constantly scanned by FreeCAD to detect selection/preselection, so it makes sense try not to overload it with unneeded scanning. Once the parts of the scenegraph that are to be selectable are inside SoFCSelection nodes, you then need to provide two methods to handle the selection path. The selection path can take the form of a string giving the names of each element in the path, or of an array of scenegraph objects. The two methods you provide are getDetailPath, which converts from a string path to an array of scenegraph objects, and getElementPicked, which takes an element which has been clicked on in the scenegraph and returns its string name (note, not its string path). Here is the molecule example above, adapted to make the elements of the molecule selectable: class Molecule: def __init__(self, obj): ''' Add two point properties ''' obj.addProperty("App::PropertyVector","p1","Line","Start point") obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(5,0,0) obj.Proxy = self def onChanged(self, fp, prop): if prop == "p1" or prop == "p2": ''' Print the name of the property that has changed ''' fp.Shape = Part.makeLine(fp.p1,fp.p2) def execute(self, fp): ''' Print a short message when doing a recomputation, this method is mandatory ''' fp.Shape = Part.makeLine(fp.p1,fp.p2) class ViewProviderMolecule: def __init__(self, obj): ''' Set this object to the proxy object of the actual view provider ''' obj.Proxy = self self.ViewObject = obj sep1=coin.SoSeparator() sel1 = coin.SoType.fromName('SoFCSelection').createInstance() # sel1.policy.setValue(coin.SoSelection.SHIFT) sel1.ref() sep1.addChild(sel1) self.trl1=coin.SoTranslation() sel1.addChild(self.trl1) sel1.addChild(coin.SoSphere()) sep2=coin.SoSeparator() sel2 = coin.SoType.fromName('SoFCSelection').createInstance() sel2.ref() sep2.addChild(sel2) self.trl2=coin.SoTranslation() sel2.addChild(self.trl2) sel2.addChild(coin.SoSphere()) obj.RootNode.addChild(sep1) obj.RootNode.addChild(sep2) self.updateData(obj.Object, 'p2') self.sel1 = sel1 self.sel2 = sel2 def getDetailPath(self, subname, path, append): vobj = self.ViewObject if append: path.append(vobj.RootNode) path.append(vobj.SwitchNode) mode = vobj.SwitchNode.whichChild.getValue() if mode >= 0: mode = vobj.SwitchNode.getChild(mode) path.append(mode) sub = Part.splitSubname(subname)[-1] if sub == 'Atom1': path.append(self.sel1) elif sub == 'Atom2': path.append(self.sel2) else: path.append(mode.getChild(0)) return True def getElementPicked(self, pp): path = pp.getPath() if path.findNode(self.sel1) >= 0: return 'Atom1' if path.findNode(self.sel2) >= 0: return 'Atom2' raise NotImplementedError def updateData(self, fp, prop): "If a property of the handled feature has changed we have the chance to handle this here" # fp is the handled feature, prop is the name of the property that has changed if prop == "p1": p = fp.getPropertyByName("p1") self.trl1.translation=(p.x,p.y,p.z) elif prop == "p2": p = fp.getPropertyByName("p2") self.trl2.translation=(p.x,p.y,p.z) def __getstate__(self): return None def __setstate__(self,state): return None def makeMolecule(): FreeCAD.newDocument() a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Molecule") Molecule(a) ViewProviderMolecule(a.ViewObject) FreeCAD.ActiveDocument.recompute()

Working with simple shapes

If your parametric object simply outputs a shape, you don't need to use a view provider object. The shape will be displayed using FreeCAD's standard shape representation: import FreeCAD as App import FreeCADGui import FreeCAD import Part class Line: def __init__(self, obj): '''"App two point properties" ''' obj.addProperty("App::PropertyVector","p1","Line","Start point") obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(1,0,0) obj.Proxy = self def execute(self, fp): '''"Print a short message when doing a recomputation, this method is mandatory" ''' fp.Shape = Part.makeLine(fp.p1,fp.p2) a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Line") Line(a) a.ViewObject.Proxy=0 # just set it to something different from None (this assignment is needed to run an internal notification) FreeCAD.ActiveDocument.recompute() Same code with use ViewProviderLine import FreeCAD as App import FreeCADGui import FreeCAD import Part class Line: def __init__(self, obj): '''"App two point properties" ''' obj.addProperty("App::PropertyVector","p1","Line","Start point") obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(100,0,0) obj.Proxy = self def execute(self, fp): '''"Print a short message when doing a recomputation, this method is mandatory" ''' fp.Shape = Part.makeLine(fp.p1,fp.p2) class ViewProviderLine: def __init__(self, obj): ''' Set this object to the proxy object of the actual view provider ''' obj.Proxy = self def getDefaultDisplayMode(self): ''' Return the name of the default display mode. It must be defined in getDisplayModes. ''' return "Flat Lines" a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Line") Line(a) ViewProviderLine(a.ViewObject) App.ActiveDocument.recompute()

Scenegraph Structure

You may have noticed that the examples above construct their scenegraphs in slightly different ways. Some use obj.addDisplayMode(node, "modename") while others use obj.SwitchNode.getChild(x).addChild(y). Each feature in a FreeCAD document is based the following scenegraph structure: RootNode \- SwitchNode \- Shaded - Wireframe - etc The SwitchNode displays only one of its children, depending on which display mode is selection in FreeCAD. The examples which use addDisplayMode are constructing their scenegraphs solely out of coin3d scenegraph elements. Under the covers, addDisplayMode adds a new child to the SwitchNode; the name of that node will match the display mode it was passed. The examples which use SwitchNode.getChild(x).addChild also construct part of their geometry using functions from the Part workbench, such as fp.Shape = Part.makeLine(fp.p1,fp.p2). This constructs the different display mode scenegraphs under the SwitchNode; when we later come to add coin3d elements to the scenegraph, we need to add them to the existing display mode scenegraphs using addChild rather than creating a new child of the SwitchNode. When using addDisplayMode() to add geometry to the scenegraph, each display mode should have its own node which is passed to addDisplayMode(); don't reuse the same node for this. Doing so will confuse the selection mechanism. It's okay if each display mode's node has the same geometry nodes added below it, just the root of each display mode needs to be distinct. Here is the above molecule example, adapted to be drawn only with Coin3D scenegraph objects instead of using objects from the Part workbench: import Part from pivy import coin class Molecule: def __init__(self, obj): ''' Add two point properties ''' obj.addProperty("App::PropertyVector","p1","Line","Start point") obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(5,0,0) obj.Proxy = self def onChanged(self, fp, prop): pass def execute(self, fp): ''' Print a short message when doing a recomputation, this method is mandatory ''' pass class ViewProviderMolecule: def __init__(self, obj): ''' Set this object to the proxy object of the actual view provider ''' self.constructed = False obj.Proxy = self self.ViewObject = obj def attach(self, obj): material = coin.SoMaterial() material.diffuseColor = (1.0, 0.0, 0.0) material.emissiveColor = (1.0, 0.0, 0.0) drawStyle = coin.SoDrawStyle() drawStyle.pointSize.setValue(10) drawStyle.style = coin.SoDrawStyle.LINES wireframe = coin.SoGroup() shaded = coin.SoGroup() self.wireframe = wireframe self.shaded = shaded self.coords = coin.SoCoordinate3() self.coords.point.setValues(0, 2, [FreeCAD.Vector(0, 0, 0), FreeCAD.Vector(1, 0, 0)]) wireframe += self.coords wireframe += drawStyle wireframe += material shaded += self.coords shaded += drawStyle shaded += material g = coin.SoGroup() sel1 = coin.SoType.fromName('SoFCSelection').createInstance() sel1.style = 'EMISSIVE_DIFFUSE' p1 = coin.SoType.fromName('SoIndexedPointSet').createInstance() p1.coordIndex.set1Value(0, 0) sel1 += p1 g += sel1 wireframe += g shaded += g g = coin.SoGroup() sel2 = coin.SoType.fromName('SoFCSelection').createInstance() sel2.style = 'EMISSIVE_DIFFUSE' p2 = coin.SoType.fromName('SoIndexedPointSet').createInstance() p2.coordIndex.set1Value(0, 1) sel2 += p2 g += sel2 wireframe += g shaded += g g = coin.SoGroup() sel3 = coin.SoType.fromName('SoFCSelection').createInstance() sel3.style = 'EMISSIVE_DIFFUSE' p3 = coin.SoType.fromName('SoIndexedLineSet').createInstance() p3.coordIndex.setValues(0, 2, [0, 1]) sel3 += p3 g += sel3 wireframe += g shaded += g obj.addDisplayMode(wireframe, 'Wireframe') obj.addDisplayMode(shaded, 'Shaded') self.sel1 = sel1 self.sel2 = sel2 self.sel3 = sel3 self.constructed = True self.updateData(obj.Object, 'p2') def getDetailPath(self, subname, path, append): vobj = self.ViewObject if append: path.append(vobj.RootNode) path.append(vobj.SwitchNode) mode = vobj.SwitchNode.whichChild.getValue() FreeCAD.Console.PrintWarning("getDetailPath: mode {} is active\n".format(mode)) if mode >= 0: mode = vobj.SwitchNode.getChild(mode) path.append(mode) sub = Part.splitSubname(subname)[-1] print(sub) if sub == 'Atom1': path.append(self.sel1) elif sub == 'Atom2': path.append(self.sel2) elif sub == 'Line': path.append(self.sel3) else: path.append(mode.getChild(0)) return True def getElementPicked(self, pp): path = pp.getPath() if path.findNode(self.sel1) >= 0: return 'Atom1' if path.findNode(self.sel2) >= 0: return 'Atom2' if path.findNode(self.sel3) >= 0: return 'Line' raise NotImplementedError def updateData(self, fp, prop): "If a property of the handled feature has changed we have the chance to handle this here" # fp is the handled feature, prop is the name of the property that has changed if not self.constructed: return if prop == "p1": p = fp.getPropertyByName("p1") self.coords.point.set1Value(0, p) elif prop == "p2": p = fp.getPropertyByName("p2") self.coords.point.set1Value(1, p) def getDisplayModes(self, obj): return ['Wireframe', 'Shaded'] def getDefaultDisplayMode(self): return 'Shaded' def setDisplayMode(self, mode): return mode def __getstate__(self): return None def __setstate__(self,state): return None def makeMolecule(): FreeCAD.newDocument() a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Molecule") Molecule(a) b=ViewProviderMolecule(a.ViewObject) a.touch() FreeCAD.ActiveDocument.recompute() return a,b a,b = makeMolecule()

Part Design scripted objects

When making scripted objects in Part Design the process is similar to the scripted objects discussed above, but with a few additional considerations. We must handle 2 shape properties, one for the shape we see in the 3D view and another for the shape used by the pattern tools, such as polar pattern features. The object shapes also needs to be fused to any existing material already in the Body (or cut from it in the case of Subtractive features). And we must account for the placement and attachment of our objects a little bit differently. Part Design scripted solid object features should be based on either PartDesign::FeaturePython, PartDesign::FeatureAdditivePython, or PartDesign::FeatureSubtractivePython rather than Part::FeaturePython. Only the Additive and Subtractive variants can be used in pattern features, and if based on Part::FeaturePython when the user drops the object into a Part Design Body it becomes a BaseFeature rather than being treated by the Body as a native Part Design object. Note: all of these are expected to be solids, so if you are making a non-solid feature it should be based on Part::FeaturePython or else the next feature in the tree will attempt to fuse to as a solid and it will fail. Here is a simple example of making a Tube primitive, similar to the Tube primitive in Part Workbench except this one will be a Part Design solid feature object. For this we will 2 separate files: pdtube.FCMacro and pdtube.py. The .FCMacro file will be executed by the user to create the object. The .py file will hold the class definitions, imported by the .FCMacro. The reason for doing it this way is to maintain the parametric nature of the object after restarting FreeCAD and opening a document containing one of our Tubes. First, the class definition file: # -*- coding: utf-8 -*- #classes should go in pdtube.py import FreeCAD, FreeCADGui, Part class PDTube: def __init__(self,obj): obj.addProperty("App::PropertyLength","Radius1","Tube","Radius1").Radius1 = 5 obj.addProperty("App::PropertyLength","Radius2","Tube","Radius2").Radius2 = 10 obj.addProperty("App::PropertyLength","Height","Tube","Height of tube").Height = 10 self.makeAttachable(obj) obj.Proxy = self def makeAttachable(self, obj): if int(FreeCAD.Version()[1]) >= 19: obj.addExtension('Part::AttachExtensionPython') else: obj.addExtension('Part::AttachExtensionPython', obj) obj.setEditorMode('Placement', 0) #non-readonly non-hidden def execute(self,fp): outer_cylinder = Part.makeCylinder(fp.Radius2, fp.Height) inner_cylinder = Part.makeCylinder(fp.Radius1, fp.Height) if fp.Radius1 == fp.Radius2: #just make cylinder tube_shape = outer_cylinder elif fp.Radius1 < fp.Radius2: tube_shape = outer_cylinder.cut(inner_cylinder) else: #invert rather than error out tube_shape = inner_cylinder.cut(outer_cylinder) if not hasattr(fp, "positionBySupport"): self.makeAttachable(fp) fp.positionBySupport() tube_shape.Placement = fp.Placement #BaseFeature (shape property of type Part::PropertyPartShape) is provided for us #with the PartDesign::FeaturePython and related classes, but it might be empty #if our object is the first object in the tree. it's a good idea to check #for its existence in case we want to make type Part::FeaturePython, which won't have it if hasattr(fp, "BaseFeature") and fp.BaseFeature != None: if "Subtractive" in fp.TypeId: full_shape = fp.BaseFeature.Shape.cut(tube_shape) else: full_shape = fp.BaseFeature.Shape.fuse(tube_shape) full_shape.transformShape(fp.Placement.inverse().toMatrix(), True) #borrowed from gears workbench fp.Shape = full_shape else: fp.Shape = tube_shape if hasattr(fp,"AddSubShape"): #PartDesign::FeatureAdditivePython and #PartDesign::FeatureSubtractivePython have this #property but PartDesign::FeaturePython does not #It is the shape used for copying in pattern features #for example in making a polar pattern tube_shape.transformShape(fp.Placement.inverse().toMatrix(), True) fp.AddSubShape = tube_shape class PDTubeVP: def __init__(self, obj): '''Set this object to the proxy object of the actual view provider''' obj.Proxy = self def attach(self,vobj): self.vobj = vobj def updateData(self, fp, prop): '''If a property of the handled feature has changed we have the chance to handle this here''' pass def getDisplayModes(self,obj): '''Return a list of display modes.''' modes=[] modes.append("Flat Lines") modes.append("Shaded") modes.append("Wireframe") return modes def getDefaultDisplayMode(self): '''Return the name of the default display mode. It must be defined in getDisplayModes.''' return "Flat Lines" def setDisplayMode(self,mode): '''Map the display mode defined in attach with those defined in getDisplayModes.\ Since they have the same names nothing needs to be done. This method is optional''' return mode def onChanged(self, vp, prop): '''Here we can do something when a single property got changed''' #FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n") pass def getIcon(self): '''Return the icon in XPM format which will appear in the tree view. This method is\ optional and if not defined a default icon is shown.''' return """ /* XPM */ static const char * ViewProviderBox_xpm[] = { "16 16 6 1", " c None", ". c #141010", "+ c #615BD2", "@ c #C39D55", "# c #000000", "$ c #57C355", " ........", " ......++..+..", " .@@@@.++..++.", " .@@@@.++..++.", " .@@ .++++++.", " ..@@ .++..++.", "###@@@@ .++..++.", "##$.@@$#.++++++.", "#$#$.$$$........", "#$$####### ", "#$$#$$$$$# ", "#$$#$$$$$# ", "#$$#$$$$$# ", " #$#$$$$$# ", " ##$$$$$# ", " ####### "}; """ def __getstate__(self): '''When saving the document this object gets stored using Python's json module.\ Since we have some un-serializable parts here -- the Coin stuff -- we must define this method\ to return a tuple of all serializable objects or None.''' return None def __setstate__(self,state): '''When restoring the serialized object from document we have the chance to set some internals here.\ Since no data were serialized nothing needs to be done here.''' return None And now the macro file to create the object: # -*- coding: utf-8 -*- #pdtube.FCMacro import pdtube #above line needed if the class definitions above are place in another file: PDTube.py #this is needed if the tube object is to remain parametric after restarting FreeCAD and loading #a document containing the object body = FreeCADGui.ActiveDocument.ActiveView.getActiveObject("pdbody") if not body: FreeCAD.Console.PrintError("No active body.\n") else: from PySide import QtGui window = FreeCADGui.getMainWindow() items = ["Additive","Subtractive","Neither additive nor subtractive"] item,ok =QtGui.QInputDialog.getItem(window,"Select tube type","Select whether you want additive, subtractive, or neither:",items,0,False) if ok: if item == items[0]: className = "PartDesign::FeatureAdditivePython" elif item == items[1]: className = "PartDesign::FeatureSubtractivePython" else: className = "PartDesign::FeaturePython" #not usable in pattern features, such as polar pattern tube = FreeCAD.ActiveDocument.addObject(className,"Tube") pdtube.PDTube(tube) pdtube.PDTubeVP(tube.ViewObject) body.addObject(tube) #optionally we can also use body.insertObject() for placing at particular place in tree

Further information

Additional pages: Scripted objects saving attributes Scripted objects migration Scripted objects with attachment Viewproviders Interesting forum threads about scripted objects: Python object attributes lost at load New FeaturePython is grey Explanation on __getstate__ and __setstate__, official documentation Eigenmode frequency always 0? how to implement python feature's setEdit properly? In addition to the examples presented here have a look at FreeCAD source code src/Mod/TemplatePyMod/FeaturePython.py for more examples.


Scripting and macros

Overview of Python scripting pages

Python related pages in the Manual: A gentle introduction Creating and manipulating geometry Creating parametric objects Creating interface tools Basics: Working with macros Script tutorial Introduction to Python Python scripting tutorial FreeCAD scripting basics Built-in workbench related: Drawing scripting (the Drawing workbench is obsolete) FEM scripting Mesh scripting Mesh: Converting between Meshes and Parts Part scripting Part: Basic shape manipulation Part: Create a ball bearing part I Part: Create a ball bearing part II Path scripting Raytracing scripting (the Raytracing workbench is obsolete) Sketcher scripting FeaturePython objects (also called 'scripted objects'): Create a FeaturePython object part I Create a FeaturePython object part II Scripted objects Scripted objects saving attributes Scripted objects migration Scripted objects with attachment Viewprovider Custom icon in tree view Properties PropertyLink: InList and OutList Methods 3D view: The Coin scenegraph Pivy User interface: PySide PySide beginner examples PySide intermediate examples PySide advanced examples PySide usage snippets Interface creation Dialog creation Dialog creation with various widgets Dialog creation reading and writing files Dialog creation setting colors Dialog creation image and animated GIF Qt Example Snippets and examples: Define a command Workbench creation Code snippets Macros recipes Line drawing function Macro Half-Hull Model Miscellaneous: Debugging Embedding FreeCAD Embedding FreeCADGui Extra python modules FreeCAD vector math library How to install macros IPython notebook integration Macro at startup Profiling Python PythonOCC Python development environment Quantity Svg namespace


Getting started

Foreword

FreeCAD is a 3D parametric modeling application. It is primarily made for mechanical design, but also serves all other uses where you need to model 3D objects with precision and control over modeling history. FreeCAD has been under development since 2002, and it offers a large list of features. Capabilities are still missing but it is powerful enough for hobbyist use, and small workshops. There is a fast-growing community of enthusiastic users who participate in the FreeCAD forum, and you can find many examples of quality projects developed with FreeCAD there. See also, FreeCAD used in production. Like all free software projects, FreeCAD depends on its community to grow, gain features, and fix bugs. Don't forget this when using FreeCAD; if you like it, you can donate and help FreeCAD in various ways, such as writing documentation and making translations. See also: Migrating to FreeCAD from Fusion360 Tutorials Video tutorials

Installing

First of all, download and install FreeCAD. See the Download page for information on current versions and updates, and the installation instructions for you operating system (Windows, Linux or Mac). There are install packages ready for Windows (.msi), Debian and Ubuntu (.deb), openSUSE (.rpm), and Mac OSX. FreeCAD is available from the package managers of many other Linux distributions. A standalone AppImage executable is also available, which will run on most recent 64-bit Linux systems. As FreeCAD is open-source, you can also grab the source code and compile it yourself.

Exploring the interface

The standard FreeCAD interface See a full explanation in Interface. 1. The main view area, which can contain different tabbed windows, principally the 3D view. 2. The 3D view, showing the geometrical objects in the document. 3. The tree view (part of the combo view), showing the hierarchy and construction history of objects in the document; it can also display the task panel for active commands. 4. The property editor (part of the combo view), which allows viewing and modifying properties of the selected objects. 5. The selection view, which indicates the objects or sub-elements of objects (vertices, edges, faces) that are selected. 6. The report view (or output window), where messages, warnings and errors are shown. 7. The Python console, where all the commands executed are printed, and where you can enter Python code. 8. The status bar, where some messages and tooltips appear. 9. The toolbar area, where the toolbars are docked. 10. The workbench selector, where you select the active workbench. 11. The standard menu, which holds basic operations of the program. The main concept behind the FreeCAD interface is that it is separated into workbenches. A workbench is a collection of tools suited for a specific task, such as working with meshes, or drawing 2D objects, or constrained sketches. You can switch the current workbench with the workbench selector. You can customize the tools included in each workbench, add tools from other workbenches or even self-created tools, that we call macros. Widely used starting points are the PartDesign Workbench and Part Workbench. When you start FreeCAD for the first time, you are presented with the Start page. Here is what it looks like for version 0.19: The Start page allows you to quickly jump to one of the most common workbenches, open one of the recent files, or see the latest news from the FreeCAD world. You can change the default workbench in the preferences.

Navigating in the 3D space

FreeCAD has several button in the Status bar or by right-clicking an empty area of the 3D view. You also have several view presets (top view, front view, etc) available in the View menu, on the View toolbar, and by numeric shortcuts (1, 2, etc...). By right-clicking on an object or on an empty area of the 3D view, you have quick access to some common operations, such as setting a particular view, or locating an object in the Tree view.

First steps with FreeCAD

FreeCAD's focus is to allow you to make high-precision 3D models, to keep tight control over those models (being able to go back into modelling history and change parameters), and eventually to build those models (via 3D printing, CNC machining or even construction worksite). It is therefore very different from some other 3D applications made for other purposes, such as animation film or gaming. Its learning curve can be steep, especially if this is your first contact with 3D modeling. If you are struck at some point, don't forget that the friendly community of users on the FreeCAD forum might be able to get you out in no time. The workbench you will start using in FreeCAD depends on the type of job you need to do: If you are going to work on mechanical models, or more generally any small-scale objects, you'll probably want to try the PartDesign Workbench. If you will work in 2D, then switch to the Draft Workbench, or the Sketcher Workbench if you need constraints. If you want to do BIM, launch the Arch Workbench. And if you come from the OpenSCAD world, try the OpenSCAD Workbench. There are also many community-developed external workbenches available. You can switch workbenches at any time, and also customize your favorite workbench to add tools from other workbenches.

Working with the PartDesign and Sketcher workbenches

The PartDesign Workbench is made to build complex objects, starting from simple shapes, and adding or removing pieces (called "features"), until you get to your final object. All the features you applied during the modelling process are stored in a separate view called the tree view, which also contains the other objects in your document. You can think of a PartDesign object as a succession of operations, each one applied to the result of the preceding one, forming one big chain. In the tree view, you see your final object, but you can expand it and retrieve all preceding states, and change any of their parameter, which automatically updates the final object. The PartDesign workbench makes heavy use of another workbench, the Sketcher Workbench. The sketcher allows you to draw 2D shapes, which are defined by applying Constraints to the 2D shape. For example, you might draw a rectangle and set the size of a side by applying a length constraint to one of the sides. That side then cannot be resized anymore (unless the constraint is changed). Those 2D shapes made with the sketcher are used a lot in the PartDesign workbench, for example to create 3D volumes, or to draw areas on the faces of your object that will then be hollowed from its main volume. This is a typical PartDesign workflow:
    Create a new sketch Draw a closed shape (make sure all points are joined) Close the sketch Expand the sketch into a 3D solid by using the pad tool Select one face of the solid Create a second sketch (this time it will be drawn on the selected face) Draw a closed shape Close the sketch Create a pocket from the second sketch, on the first object
Which gives you an object like this: At any moment, you can select the original sketches and modify them, or change the extrusion parameters of the pad or pocket operations, which will update the final object.

Working with the Draft and Arch workbenches

The Draft Workbench and Arch Workbench behave a bit differently than the other workbenches above, although they follow the same rules, which are common to all of FreeCAD. In short, while the Sketcher and PartDesign are made primarily to design single pieces, Draft and Arch are made to ease your work when working with several, simpler objects. The Draft Workbench offers you 2D tools somewhat similar to what you can find in traditional 2D CAD applications such as AutoCAD. However, 2D drafting being far away from the scope of FreeCAD, don't expect to find there the full array of tools that these dedicated applications offer. Most of the Draft tools work not only in a 2D plane but also in the full 3D space, and benefit from special helper systems such as Work planes and object snapping. The Arch Workbench adds BIM tools to FreeCAD, allowing you to build architectural models with parametric objects. The Arch workbench relies extensively on other modules such as Draft and Sketcher. All the Draft tools are also present in the Arch workbench, and most Arch tools make use of the Draft helper systems. A typical workflow with Arch and Draft workbenches might be:
    Draw a couple of lines with the Draft Line tool Select each line and press the Wall tool to build a wall on each of them Join the walls by selecting them and pressing the Arch Add tool Create a floor object, and move your walls in it from the Tree view Create a building object, and move your floor in it from the Tree view Create a window by clicking the Window tool, select a preset in its panel, then click on a face of a wall Add dimensions by first setting the working plane if necessary, then using the Draft Dimension tool
Which will give you this: More on the Tutorials page.

Addons, Macro and External workbenches

FreeCAD, as an open source software, offers the possibility to supplement its workbenches with addons. The Addon principle is based on the development of a workbench complement. Any user can develop a function that he or she deems to be missing for her/his own needs or, ultimately, for the community. With the forum, the user can request an opinion, help on the forum. It can share, or not, the object of its development according to copyright rules to define. Free to her/him. To develop, the user has available scripting functions. There are two types of addons:
    Macros: short snippets of Python code that provide a new tool or functionality. Macros usually start as a way to simplify or automate the task of drawing or editing a particular object. If many of these macros are collected inside a directory, the entire directory may be distributed as a new workbench. External workbenches: collections of tools programmed in Python or C++ that extend FreeCAD in an important way. If a workbench is sufficiently developed and is well documented, it may be included as one of the base workbenches in FreeCAD. Under External workbenches, you'll find the principle and a list of existing library.

Scripting

And finally, one of the most powerful features of FreeCAD is the scripting environment. From the integrated python console (or from any other external Python script), you can gain access to almost any part of FreeCAD, create or modify geometry, modify the representation of those objects in the 3D scene or access and modify the FreeCAD interface. Python scripting can also be used in macros, which provide an easy method to create custom commands.

What's new

See the release notes for the detailed list of features.


Workbenches

FreeCAD, like many modern design applications such as Revit or CATIA, is based on the concept of Workbench. A workbench can be considered as a set of tools specially grouped for a certain task. In a traditional furniture workshop, you would have a work table for the person who works with wood, another one for the one who works with metal pieces, and maybe a third one for the guy who mounts all the pieces together. In FreeCAD, the same concept applies. Tools are grouped into workbenches according to the tasks they are related to. When you switch from one workbench to another, the tools available on the interface change. Toolbars, command bars and possibly other parts of the interface switch to the new workbench, but the contents of your scene doesn't change. You could, for example, start drawing 2D shapes with the Draft Workbench, then work further on them with the Part Workbench. Note that sometimes a Workbench is referred to as a Module. However, Workbenches and Modules are different entities. A Module is any extension of FreeCAD, while a Workbench is a special type of Module with a GUI configuration (toolbars and menus).

Built-in workbenches

The following workbenches are bundled with every FreeCAD installation: Std Base. This is not really a workbench, but rather a category of 'standard' commands and tools that can be used in all workbenches. The Arch Workbench for working with architectural elements. The Draft Workbench contains 2D tools and basic 2D and 3D CAD operations. The FEM Workbench provides Finite Element Analysis (FEA) workflow. The Image Workbench for working with bitmap images. The Inspection Workbench is made to give you specific tools for examination of shapes. It is still under development. The Mesh Workbench for working with triangulated meshes. The OpenSCAD Workbench for interoperability with OpenSCAD and repairing constructive solid geometry (CSG) model history. The Part Workbench for working with CAD parts. The Part Design Workbench for building Part shapes from sketches. The Path Workbench is used to produce G-Code instructions. It is still under development. The Points Workbench for working with point clouds. The Raytracing Workbench for working with ray-tracing (rendering). The Reverse Engineering Workbench is intended to provide specific tools to convert shapes/solids/meshes into parametric FreeCAD-compatible features. It is still under development. The Robot Workbench for studying robot movements. The Sketcher Workbench for working with geometry-constrained sketches. The Spreadsheet Workbench for creating and manipulating spreadsheet data. The Start Center Workbench allows you to quickly jump to one of the most common workbenches. The Surface Workbench provides tools to create and modify surfaces. It is similar as the Part Shape builder Face from edges. The TechDraw Workbench for producing technical drawings from 3D models. It is the successor of the Drawing Workbench. The Test Framework Workbench is for debugging FreeCAD. The Web Workbench provides you with a browser window instead of the 3D view within FreeCAD.

Deprecated

The following workbenches are still included in the base installation for compatibility purposes, but they should no longer be used. The Complete Workbench holds all commands and features from all workbenches that met certain quality criteria. obsolete in version 0.17 The Drawing Workbench was used for producing technical drawings but has now been deprecated. It is still needed to read old FreeCAD files that contain objects created with this workbench. The TechDraw Workbench is its more advanced replacement. obsolete in version 0.17

External workbenches

FreeCAD workbenches are easy to program in Python, there are therefore many people developing additional workbenches outside of the FreeCAD main development area. The Addon manager. New workbenches are always in development, stay tuned!


Manual:BIM modeling

This documentation is not finished. Please help and contribute documentation. GuiCommand model explains how commands should be documented. Browse Category:UnfinishedDocu to see more incomplete pages like this one. See Category:Command Reference for all commands. BIM stands for Building Information Modeling. The exact definition of what it is varies, but we can simply say that it is how buildings and other large structures like bridges, tunnels, etc... are modeled today. BIM models are usually based on 3D models, and also include a series of additional layers of information, such as materials information, relationships to other objects or models, or special instructions for building or maintenance. This extra information permits all kinds of advanced analysis of the model, such as structural resistance, cost and construction time estimations, or calculations of energy consumption. The Arch Workbench of FreeCAD implements a series of tools and facilities for BIM modeling. Although it has a different purpose, it is made to work in tight integration with the rest of FreeCAD: Anything made with any other workbench of FreeCAD can become an Arch object, or be used as a base for an Arch object. As in the PartDesign Workbench, the objects produced by the Arch Workbench are meant to be built in the real world. Therefore, they need to be solid. The Arch tools usually take care of that automatically, and also provide utility tools to help you check the validity of objects. The Arch Workbench also includes all the tools from the Draft Workbench, and uses its grid and snapping system. Before beginning, it is always a good idea to browse through the preferences pages of both Draft and Arch and set the default settings to your liking. In this chapter, we will see how to model this small building: and produce a plan and a section view from it: Create a new document, and switch to the Arch Workbench. Open menu Edit → Preferences → Draft → Grid and Snapping and set: Main lines every 10. Grid spacing 1000mm to have a one meter-based grid, which is convenient for the size of our building. Grid size 100 lines. On the snapping toolbar make sure the grid snap button is enabled, so we can use the grid as much as possible. If you do not see the axes then click the toggle draft grid button. Set the Working Plane to XY plane Zoom out and pan so you can see the area from (0,0) to (4,3). See the Mouse navigation for instructions. Draw four lines with the Draft Line tool. You can enter coordinates manually, or simply pick the points on the grid with the mouse: From point (0,0) to point (0,3) From point (0,3) to point (4,3) From point (4,3) to point (4,0) From point (4,0) to point (0,0) NOTE: Due to a bug in version 0.18, make sure you do the lines in this order and this direction. Notice that we drew always in the same direction (clockwise). This is not necessary, but will ensure that the walls that we will build next all have the same left and right directions. You might also think we could simply have drawn a rectangle here, which is true. But the four lines will allow us to illustrate better how to add one object into another. Once your have created the lines check their start and end points and adjust if necessary to get them exactly correct.
Select the first line, then press the Wall button. Repeat this for the 3 other lines, until you have 4 walls. Select the four walls, and set their Height property to 3.00m and their Alignment property to left. If you didn't draw the lines in the same order as we did above, some of the walls might have their left and right directions flipped, and might need to be set to right instead. You will obtain four intersecting walls, on the inside of the baselines: Now we need to join these walls together, so they intersect properly. This is not necessary when your walls are drawn in a way that they already connect cleanly, but here we need to, since they are intersecting. In Arch, this is done by electing one of the walls to be the "host", and adding the others to it, as "additions". All arch objects can have any number of additions (objects whose geometry will be added to the host's geometry), and subtractions (objects whose geometry will be subtracted). The additions and subtractions of an object can be managed anytime by double-clicking the object in the tree. Select the four walls with Ctrl pressed, the last one being the wall that you chose to become the host Press the Add button. The four walls have now been turned into one: The individual walls are however still accessible, by expanding the wall in the tree view. Let's now place a door. In FreeCAD, doors are considered a special case of windows, so this is done using the Window tool. Start by selecting the wall. This is not necessary, but a good habit to take. If an object is selected when starting the window tool, you will force the window to be inserted in that object, even if you snap to another object. Set the Working Plane to auto so we are not restricted to the ground plane Press the Window button. In the window creation panel, select the Simple door preset, and set its Width to 0.9m and its Height to 2.1m Make sure the Near snap location is turned on, so we can snap on faces Place your window roughly on the middle of the front face of the wall: After clicking, our window is placed on the correct face, but not exactly where we want: We can now set the precise location by expanding the wall and the window objects in the tree view, and changing the Placement property of the base sketch of our door. Set its position to x = 2m, y = 0, z = 0. Our window is now exactly where we want it: Repeat the operation to place a window: Select the wall, press the window tool, select the Open 2-pane preset, and place a 1m x 1m window in the same face as the door. Set the placement of the underlying sketch to position x = 0.6m, y = 0, z = 1.1m, so the upper line of the window is aligned to the top of the door. Windows are always built on sketches. It is easy to create custom windows by first creating a sketch on a face, then turning it into a window by selecting it, then pressing the window button. Then, the window creation parameters, that is, which wires of the sketch must be extruded and how much, can be defined by double-clicking the window in the tree view. Now, let's create a slab: Set the Working Plane to XY plane Create a rectangle with a length of 5m, a height of 4m, and place it at position x:-0.5m, y:-0.5m, z:0. Select the rectangle Click the structure tool to create a slab from the rectangle Set the height property of the slab to 0.2m and its normal direction to (0,0,-1) because we want it to extrude downwards. We could also simply have moved it 0.2m down, but it is always good practice to keep extruded objects at the same place as their base profile. Set the Role property of the slab to slab. This is not necessary in FreeCAD, but is important for IFC export, as it will ensure that the object is exported with the correct IFC type. Let's now use one of the structural presets to make a metallic beam. Click the structure button, select a HEB 180 preset, and set its height to 4m. Place it anywhere: Adjust its placement by setting its Angle to 90° in the (1,0,0) axis, and its position to x:90mm, y:3.5m, z:3.09m. This will position the beam exactly on one of the side walls: We need now to duplicate this beam a couple of times. We could do that one by one using the clone tool, but there is a better way, to do all the copies at once using an array: Select the beam Press the Draft OrthoArray button Set the Number of elements for the X direction of the array to 6, set the number for the Y and Z direction to 1, and press OK. Expand the interval X property of the array, and press the small expression icon at the right side of the X field. This will open an expressions editor: Write (4m-180mm)/5 in the expression field, and press OK. This will set the x value to 0.764 (4m is the total length of our front wall, 180mm is the width of the beam, which is why it is called HEB180, and we want a fifth of that space as interval between each beam): We can now easily build a simple slab on top of them, by drawing a rectangle directly on the top plane of the beams. Select a top face of one of the beams Press the working plane button. The working plane is now set to that face. Create a rectangle, snapping to two opposite points of the border beams: Select the rectangle Click the structure button and create a slab with a height of 0.2m. That's it, our model is now complete. We should now organize it so it exports correctly to IFC. The IFC format requires that all objects of a building are inside a building object, and optionally, inside a story. It also requires that all buildings are placed on a site, but the IFC exporter of FreeCAD will add a default site automatically if needed, so we don't need to add one here. Select the two slabs, the wall, and the array of beams Press the Floor button Select the floor we just created Press the Building button Our model is now ready to export: The IFC format is one of the most precious assets in a free BIM world, because it allows the exchange of data between any application and actor of the construction world, in an open manner (the format is open, free and maintained by an independent consortium). Exporting your BIM models as IFC ensures that anyone can see and analyze them, no matter the application used. In FreeCAD, IFC import and export is done by interfacing with another piece of software, called IfcOpenShell. To be able to export to IFC from FreeCAD, the IfcOpenShell-python package must be installed on your system. Be sure to select one which uses the same python version as FreeCAD. The python version that FreeCAD uses is informed when opening the View -> Panels -> Python console panel in FreeCAD. When that is done, we can now export our model: Select the top object you want to export, that is, the Building object. Select menu File -> Export -> Industry Foundation Classes and save your file. The resulting IFC file can now be opened in a wide range of applications and viewers (the image below shows the file opened in the free IfcPlusPlus viewer). Checking the exported file in such a viewer application before distributing it to other people is important to check that all the data contained in the file is correct. FreeCAD itself can also be used to re-open the resulting IFC file. We will now place some dimensions. Unlike the previous chapter, where we drew all the dimensions directly on the Drawing sheet, we will use another method here, and place Draft dimensions directly in the 3D model. These dimensions will then be placed on the Drawing sheet automatically. We will first make two groups for our dimensions, one for the dimensions that will appear in the plan view, and another for those that appear on the elevation. Right-click the "house" document in the tree view, and create two new groups: Plan dimensions and Elevation dimensions. Set the Working Plane to XY plane Make sure the restrict snap location is turned on, so everything you draw stays on the working plane. Draw a couple of Dimensions, for example as on the image below. Pressing Shift and Ctrl while snapping the dimension points will give you additional options. Select all your dimensions, and drag them to the Plan dimensions group in the tree view Set the Working Plane to XZ plane, that is, the frontal vertical plane. Repeat the operation, draw a couple of dimensions, and place them in the Elevation dimensions group. We will now prepare a set of views from our model, to be placed on a Drawing page. We can do that with the tools from the Drawing Workbench, as we have seen in the previous chapter, but the Arch Workbench also offers an all-in-one advanced tool to produce plan, section and elevation views, called Section Plane. We will now add two of these section planes, to create a plan view and an elevation view. Select the building object in the tree view Press the Section Plane button. Set its Display Height property to 5m, its Display Length to 6m, so we encompass our house (this is not needed, but will look better, as it will show naturally what it is used for), and its Placement position at x:2m, y:1.5m, z:1.5m. Check the list of objects considered by the Section Plane by double-clicking it in the tree view. Section Planes only render specified objects from the model, not all of them. The objects considered by the Section Plane can be changed here. Repeat the operation to create another section plane, give it the same display length and height, and give it the following Placement: position: x:2m, y:-2m, z:1.5m, angle: 90°, axis: x:1, y:0, z:0. Make sure this new section plane also considers the building object. Now we have everything we need, and we can create our Drawing page. Start by switching to the A3 page (or select another template if you wish). Select the first section plane, used for the plan view Press the Draft View button. This tool offers a couple of additional features over the standard Drawing View tool, and supports the Section Planes from the Arch Workbench. Give the new view the following properties: X: 50 Y: 140 Scale: 0.03 Line width: 0.15 Show Cut True Show Fill: True Select the other section plane, and create a new Draft View, with the following properties: X: 250 Y: 150 Scale: 0.03 Rendering: Solid We will now create two more Draft Views, one for each group of dimensions. Select the Plan dimensions group Press the Draft View button. Give the new view the following properties: X: 50 Y: 140 Scale: 0.03 Line width: 0.15 Font size: 10mm Repeat the operation for the other group, with the following settings: X: 250 Y: 150 Scale: 0.03 Line width: 0.15 Font size: 10mm Direction: 0,-1,0 Rotation: 90° Our page is now ready, and we can export it to SVG or DXF formats, or print it. The SVG format allows you to open the file using illustration applications such as Inkscape, with which you can quickly enhance technical drawings and turn them into much nicer presentation drawings. It offers many more possibilities than the DXF format.

Downloads

The file produced during this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/house.FCStd The IFC file exported from the above file: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/house.ifc The SVG file exported from the above file: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/house.svg

Related

BIM Workbench The Arch Workbench The Draft working plane The Draft snapping settings The expressions system The IFC format IfcOpenShell IfcPlusPlus Inkscape


Part Module

Introduction

The solid modelling capabilities of FreeCAD are based on the OpenCASCADE Technology (OCCT) kernel, a professional-grade CAD system that features advanced 3D geometry creation and manipulation. The Part Workbench is a layer sitting on top of the OCCT libraries, that gives the user access to OCCT geometric primitives and functions. Essentially all 2D and 3D drawing functions in every workbench ( PartDesign, etc.), are based on these functions exposed by the Part Workbench. Therefore, the Part Workbench is considered the core component of the modelling capabilities of FreeCAD. A more detailed discussion of Part workbench versus Part Design workbench can be found here: Part and Part Design. The objects created with the Part Workbench are relatively simple; they are intended to be used with boolean operations (unions and cuts) in order to build more complex shapes. This modeling paradigm is known as the constructive solid geometry (CSG) workflow, and it was the traditional methodology used in early CAD systems. On the other hand, the PartDesign Workbench provides a more modern workflow to constructing shapes: it uses a parametrically defined sketch, that is extruded to form a basic solid body, which is then modified by parametric transformations (feature editing), until the final object is obtained. Part objects are more complex than mesh objects created with the Mesh Workbench, as they permit more advanced operations like coherent boolean operations, modifications history, and parametric behaviour. The Part Workbench is the basic layer that exposes the OCCT drawing functions to all workbenches in FreeCAD.

Tools

The tools are located in the Part menu or the Measure menu.

Primitives

These are tools for creating primitive objects. Box: Creates a box. Cylinder: Creates a cylinder. Sphere: Creates a sphere. Cone: Creates a cone. Torus: Creates a torus (ring). Tube: Creates a tube. introduced in version 0.19 Primitives: A tool to create one of the following primitives: Plane: Creates a plane. Box: Creates a box. This object can also be created with the Box tool. Cylinder: Creates a cylinder. This object can also be created with the Cylinder tool. Cone: Creates a cone. This object can also be created with the Cone tool. Sphere: Creates a sphere. This object can also be created with the Sphere tool. Ellipsoid: Creates a ellipsoid. Torus: Creates a torus. This object can also be created with the Torus tool. Prism: Creates a prism. Wedge: Creates a wedge. Helix: Creates a helix. Spiral: Creates a spiral. Circle: Creates a circular edge. Ellipse: Creates an elliptical edge. Point: Creates a point (vertex). Line: Creates a line (edge). Regular Polygon: Creates a regular polygon. Builder: Creates shapes from various primitives.

Creation and modification

These are tools for creating new and modifying existing objects. Extrude: Extrudes planar faces. Revolve: Creates a solid by revolving an object (not a solid) around an axis. Mirror: Mirrors the selected object across a mirror plane. Fillet: Fillets (rounds) edges of an object. Chamfer: Chamfers edges of an object. Make face from wires: Makes a face from a set of wires (contours). introduced in version 0.19 Ruled Surface: Creates a ruled surface. Loft: Lofts from one profile to another. Sweep: Sweeps one or more profiles along a path. Section: Creates a section by intersecting an object with a section plane. Cross sections...: Creates one or more cross-sections through an object. Offset tools: 3D Offset: Constructs a parallel shape at a certain distance from an original. 2D Offset: Constructs a parallel wire at certain distance from an original, or enlarges/shrinks a planar face. Thickness: Hollows out a solid. Projection on surface: Projects a logo, text or any face, wire or edge onto a surface. introduced in version 0.19 Attachment: Attaches an object to another object.

Boolean

These tools perform boolean operations. Compound Tools: Make compound: Creates a compound from the selected objects. Explode Compound: Splits up compounds. Compound Filter: Extracts the individual pieces from compounds. Boolean: Performs boolean operations on objects. Cut: Cuts (subtracts) one object from another. Fuse: Fuses (unions) two objects. Common: Extracts the common (intersection) part of two objects. Join features: Connect: Connects interiors of walled objects. Embed: Embeds a walled object into another walled object. Cutout: Creates a cutout in a wall of an object for another walled object. Splitting tools: Boolean fragments: Creates all pieces obtained from Boolean operations. Slice a part: Slices and splits an object by intersecting it with other objects. Slice: Slices an object by intersecting it with other objects. XOR: Removes space shared by an even number of objects (symmetric version of Cut).

Measure

Measure: Tools for linear and angular measurements. Measure Linear: Creates a linear measurement. Measure Angular: Creates an angular measurement. Measure Refresh: Updates all measurements. Clear All: Clears all measurements. Toggle All: Shows or hides all measurements. Toggle 3D: Shows or hides 3D measurements. Toggle Delta: Shows or hides delta measurements.

Other tools

Import: Imports from *.IGES, *.STEP, or *.BREP files. Export: Exports to *.IGES, *.STEP, or *.BREP files. BoxSelection: Selects faces from a rectangular area. Shape from Mesh: Creates a shape object from a mesh object. Points from mesh: Creates a shape object made of points from a mesh object. introduced in version 0.19 Convert to solid: Converts a shape object to a solid object. Reverse shapes: Flips the normals of all faces of selected objects. Create a copy: Create simple copy: Creates a simple copy of a selected object. Create transformed copy: Creates a transformed copy of a selected object. introduced in version 0.19 Create shape element copy: Creates a copy from an element (vertex, edge, face) of a selected object. introduced in version 0.19 Refine shape: Cleans faces by removing unnecessary lines. Check geometry: Checks the geometry of selected objects for errors. Defeaturing: Removes features from an object.

Context menu items

Appearance: Determines the appearance of a whole object (color, transparency etc.). Set colors: Assigns colors to individual faces of objects.

Preferences

Preferences: Preferences available for Part Tools (the Part workbench also uses the PartDesign Preferences). Import Export Preferences: Preferences available for importing from and exporting to different file formats. Fine-tuning: Some extra parameters to fine-tune Part behavior.

Scripting

See Part scripting.

Tutorials

Import from STL or OBJ : How to import STL/OBJ files in FreeCAD Export to STL or OBJ : How to export STL/OBJ files from FreeCAD Whiffle Ball tutorial : How to use the Part Module


PartDesign Workbench

Introduction

The PartDesign Workbench provides advanced tools for modeling complex solid parts. It is mostly focused on creating mechanical parts that can be manufactured and assembled into a finished product. Nevertheless, the created solids can be used in general for any other purpose such as architectural design, finite element analysis, or machining and 3D printing. The PartDesign Workbench is intrinsically related to the Sketcher Workbench. The user normally creates a Sketch, then uses the PartDesign Pad tool to extrude it and create a basic solid, and then this solid is further modified. While the Part Workbench is based on a constructive solid geometry (CSG) methodology for building shapes, the PartDesign Workbench uses a parametric, feature editing methodology, which means a basic solid is sequentially transformed by adding features on top until the final shape is obtained. See the feature editing page for a more complete explanation of this process, and then see Creating a simple part with PartDesign to get started with creating solids. A more detailed discussion of Part workbench versus Part Design workbench can be found here: Part and Part Design. The bodies created with PartDesign are often subject to the topological naming problem which causes internal features to be renamed when the parametric operations are modified. This problem can be minimized by following the best practices described in the feature editing page, and by taking advantage of datum objects as support for sketches and features.

Tools

The Part Design tools are all located in the Part Design menu and the PartDesign toolbar that appear when you load the Part Design workbench.

Structure tools

These tools are in fact not part of the PartDesign Workbench. They belong to the Std Base system. They were developed in v0.17 with the intention that they would be useful to organize a model, and create assemblies; as such, they are very useful when working with bodies created with this workbench. Part: adds a new Part container in the active document and makes it active. Group: adds a Group container in the active document, which allows organizing the objects in the tree view.

Part Design Helper tools

Create body: creates a Body object in the active document and makes it active. Create sketch: creates‎ a new sketch on a selected face or plane. If no face is selected while this tool is executed, the user is prompted to select a plane from the Tasks panel. The interface then switches to the Sketcher Workbench in sketch editing mode. Edit sketch: Edit the selected Sketch. Map sketch to face: Maps a sketch to a previously selected plane or a face of the active body.

Part Design Modeling tools

Datum tools

Create a datum point: creates a datum point in the active body. Create a datum line: creates a datum line in the active body. Create a datum plane: creates a datum plane in the active body. Create a local coordinate system: creates a local coordinate system attached to datum geometry in the active body. Create a shape binder: creates a shape binder in the active body. Create a sub-object shape binder: creates a shape binder to a subelement, like edge or face from another body, while retaining the relative position of that element. introduced in version 0.19 Create a clone: creates a clone of the selected body.

Additive tools

These are tools for creating base features or adding material to an existing solid body. Pad: extrudes a solid from a selected sketch. Revolution: creates a solid by revolving a sketch around an axis. The sketch must form a closed profile. Additive loft: creates a solid by making a transition between two or more sketches. Additive pipe: creates a solid by sweeping one or more sketches along an open or closed path. Additive helix: creates a solid by sweeping a sketch along a helix. introduced in version 0.19 Create an additive primitive: adds an additive primitive to the active body. Additive box: creates an additive box. Additive cone: creates an additive cone. Additive cylinder: creates an additive cylinder. Additive ellipsoid: creates an additive ellipsoid. Additive prism: creates an additive prism. Additive sphere: creates an additive sphere. Additive torus: creates an additive torus. Additive wedge: creates an additive wedge.

Subtractive tools

These are tools for subtracting material from an existing body. Pocket: creates a pocket from a selected sketch. Hole: creates a hole feature from a selected sketch. The sketch must contain one or multiple circles. Groove: creates a groove by revolving a sketch around an axis. Subtractive loft: creates a solid shape by making a transition between two or more sketches and subtracts it from the active body. Subtractive pipe: creates a solid shape by sweeping one or more sketches along an open or closed path and subtracts it from the active body. Subtractive helix: creates a solid shape by sweeping a sketch along a helix and subtracts it from the active body. introduced in version 0.19 Create a subtractive primitive: adds a subtractive primitive to the active body. Subtractive box: adds a subtractive box to the active body. Subtractive cone: adds a subtractive cone to the active body. Subtractive cylinder: adds a subtractive cylinder to the active body. Subtractive ellipsoid: adds a subtractive ellipsoid to the active body. Subtractive prism: adds a subtractive prism to the active body. Subtractive sphere: adds a subtractive sphere to the active body. Subtractive torus: adds a subtractive torus to the active body. Subtractive wedge: adds a subtractive wedge to the active body.

Transformation tools

These are tools for transforming existing features. They will allow you to choose which features to transform. Mirrored: mirrors one or more features on a plane or face. Linear Pattern: creates a linear pattern based on one or more features. Polar Pattern: creates a polar pattern of one or more features. Create MultiTransform: creates a pattern with any combination of the other transformations.

Dress-up tools

These tools apply a treatment to the selected edges or faces. Fillet: fillets (rounds) edges of the active body. Chamfer: chamfers edges of the active body. Draft: applies an angular draft to selected faces of the active body. Thickness: creates a thick shell from the active body and opens selected face(s).

Boolean

Boolean operation: imports one or more Bodies or PartDesign Clones into the active body and applies a Boolean operation.

Extras

Some additional functionality found in the Part Design menu: Migrate: migrates files created with older FreeCAD versions. If the file is pure PartDesign feature-based, migration should succeed. If the file contains mixed Part/Part Design/Draft objects, the conversion will most likely fail. Sprocket design wizard: creates a sprocket profile that can be padded. introduced in version 0.19 Involute gear design wizard: creates an involute gear profile that can be padded. Shaft design wizard: Generates a shaft from a table of values and allows to analyze forces and moments. The shaft is made with a revolved sketch that can be edited.

Context Menu items

Set tip: redefines the tip, which is the feature exposed outside of the Body. Move object to other body: moves the selected sketch, datum geometry or feature to another Body. Move object after other object: allows reordering of the Body tree by moving the selected sketch, datum geometry or feature to another position in the list of features.

Items shared with the Part workbench

Appearance: determines appearance of the whole part (color transparency etc.). Set colors: assigns colors to part faces.

Preferences

Preferences: preferences available for PartDesign Tools. Fine tuning: some extra parameters to fine-tune PartDesign behavior.

Tutorials

How to use FreeCAD, a website describing the workflow for mechanical design. Creating a simple part with PartDesign Basic Part Design Tutorial PartDesign Bearingholder Tutorial I (needs updating) PartDesign Bearingholder Tutorial II (needs updating)


Manual:Modeling for product design

Product design is originally a commercial term, but in the 3D world, it often means modeling something with the idea to have it 3D-printed or, more generally, manufactured by a machine, for example a 3D printer or a CNC machine. When you print objects in 3D, it is of ultimate importance that your objects are solid. As they will become real, solid objects, this is obvious. Nothing prevents them from being hollow inside, of course. But you always need to have a clear notion of which point is inside the material, and which point is outside, because the 3D printer or the CNC machine needs to know exactly what is filled with material and what is not. For this reason, in FreeCAD, the PartDesign Workbench is the perfect tool to build such pieces, because it will always take care for you that your objects stay solid and buildable. To illustrate how the PartDesign Workbench works, let's model this well-known piece of Lego: The cool thing with Lego pieces is that the dimensions are easy to obtain on the Internet, at least for the standard pieces. These are pretty easy to model and print on a 3D printer, and with a bit of patience (3D printing often requires much adjustment and fine-tuning) you can make pieces that are totally compatible and click perfectly into original Lego blocks. In the example below, we will make a piece that is 1.5 times bigger than the original. We will now use exclusively the Sketcher and PartDesign tools. Since all the tools from the Sketcher Workbench are also included in the Part Design Workbench, we can stay in Part Design and we will not need to switch back and forth between the two. Part Design objects are fully based on Sketches. A Sketch is a 2D object, made of linear segments (lines, arcs of circle or ellipses) and constraints. These constraints can be applied either on linear segments or on their endpoints or center points, and will force the geometry to adopt certain rules. For example, you can place a vertical constraint on a line segment to force it to stay vertical, or a position (lock) constraint on an endpoint to prohibit it to move. When a sketch has an exact amount of constraints that prohibits any point of the sketch to be moved anymore, we talk about a fully constrained sketch. When there are redundant constraints, that could be removed without allowing the geometry to be moved, it is called over-constrained. This should be avoided, and FreeCAD will notify you if such a case occurs. Sketches have an edit mode, where their geometry and constraints can be changed. When you are done with editing, and leave edit mode, sketches behave like any other FreeCAD object, and can be used as building blocks for all the Part Design tools, but also in other workbenches, such as Part or Arch. The Draft workbench also has a tool that converts Draft objects to Sketches, and vice-versa. Let's start by modeling a cubic shape that will be the base of our Lego brick. Later on we will carve the insides, and add the 8 dots on top of it. So let's start this by making a rectangular sketch that we will then extrude: Switch to the PartDesign Workbench Click on the New Sketch button. A dialog will appear asking where you want to lie the sketch, choose the XY plane, which is the "ground" plane. The sketch will be created and will immediately be switched to edit mode, and the view will be rotated to look at your sketch orthogonally. Now we can draw a rectangle, by selecting the Rectangle tool and clicking 2 corner points. You can place the two points anywhere, since their correct location will be set in the next step. You will notice that a couple of constraints have automatically been added to our rectangle: the vertical segments have received a vertical constraint, the horizontal ones a horizontal constraint, and each corner a point-on-point constraint that glues the segments together. You can experiment moving the rectangle around by dragging its lines with the mouse, all the geometry will keep obeying the constraints. Now, let's add three more constraints: Select one of the vertical segments and add a Vertical Distance Constraint. Give it a size of 23.7mm. Select one of the horizontal segments and add a Horizontal Distance Constraint. Make it 47.7mm. Finally, select one of the corner points, then the origin point (which is the dot at the crossing of the red and green axes), then add a Coincident Constraint. The rectangle will then jump to the origin point, and your sketch will turn green, meaning it is now fully constrained. You can try moving its lines or points, nothing will move anymore. Note that the last point-on-point constraint was not absolutely necessary. You are never forced to work with fully constrained sketches. However, if we are going to print this block in 3D, it will be necessary to maintain our piece close to the origin point (which will be the center of the space where the printer head can move). By adding that constraint we are making sure that our piece will always stay "anchored" to that origin point. Our base sketch is now ready, we can leave edit mode by pressing the Close button on top of its task panel, or simply by pressing the Escape key. If needed later on, we can reenter edit mode anytime by double-clicking the sketch in the tree view. Let's extrude it by using the Pad tool, and giving it a distance of 14.4mm. The other options can be left at their default values: The Pad behaves very much like the Extrude tool that we used in the previous chapter. There are a couple of differences, though, the main one being that a pad cannot be moved. It is attached forever to its sketch. If you want to change the position of the pad, you must move the base sketch. In the current context, where we want to be sure nothing will move out of position, this is an additional security. We will now carve the inside of the block, using the Pocket tool, which is the PartDesign version of Part Cut. To make a pocket, we will create a sketch on the bottom face of our block, which will be used to remove a part of the block. With the bottom face selected, press the New sketch button. Draw a rectangle on the face. We will now constrain the rectangle in relation to the bottom face. To do this, we need to "import" some edges of the face with the External geometry tool. Use this tool on the two vertical lines of the bottom face: You will notice that only edges from the base face can be added by this tool. When you create a sketch with a face selected, a relation is created between that face and the sketch, which is important for further operations. You can always remap a sketch to another face later with the Map sketch tool. The external geometry is not "real", it will be hidden when we leave edit mode. But we can use it to place constraints. Place the 4 following constraints: Select the top left point of the rectangle and the top point of the imported line and add a Horizontal Distance Constraint of 1.8mm Select again the top left point of the rectangle and the top point of the imported line and add a Vertical Distance Constraint of 1.8mm Select the bottom right point of the rectangle and the bottom point of the right imported line and add a Horizontal Distance Constraint of 1.8mm Select again the bottom right point of the rectangle and the bottom point of the right imported line and add a Vertical Distance Constraint of 1.8mm Leave edit mode and we can now perform the pocket operation: With the sketch selected, press the Pocket button. Give it a length of 12.6mm, which will leave the upper face of our pad with a thickness of 1.8mm (remember, the total height of our pad was 14.4mm). We will now attack the 8 dots on the top face. To do this, since they are a repetition of a same feature, we will use the handy Linear pattern tool of the Part Design Workbench, which allows to model once and repeat the shape. Start by selecting the top face of our block Create a New sketch. Create two circles. For each circle, select it and add a Radius Constraint of 3.6mm to each of them Import the left edge of the base face with the External geometry tool. Place two vertical constraints and two horizontal constraints of 6mm between the center point of each circle and the corner points of the imported edge, so each circle has its center at 6mm from the border of the face: Notice how, once again, when you lock the position and dimension of everything in your sketch, it becomes fully constrained. This always keeps you on the safe side. You could change the first sketch now, everything we did afterwards would keep tight. Leave edit mode, select this new sketch, and create a Pad of 2.7mm: Notice that, as earlier with the pocket, since we used the top face of our base block as a base for this latest sketch, any PartDesign operation we do with this sketch will correctly be built on top of the base shape: The two dots are not independent objects, they have been extruded directly from our brick. This is the great advantage of working with the Part Design Workbench, as long as you take care of always building one step on top of the previous one, you are actually building one final solid object. We can now duplicate our two dots four times, so we get eight. Select the latest Pad we just created. Press the Linear pattern button. Give it a length of 36mm (which is the total "span" we want our copies to fit in), in the "horizontal sketch axis" direction, and make it 4 occurrences: Once again, see that this is not just a duplication of an object, it is a *feature* of our shape that has been duplicated, the final object is still only one solid object. Now let's work on the three "tubes" that fill the void we created on the bottom face. We have several possibilities: create a sketch with three circles, pad it then pocket it three times, or create a base sketch with one circle inside the other and pad it to form the complete tube already, or even other combinations. Like always in FreeCAD, there are many ways to achieve the same result. Sometimes one way will not work the way we want, and we must try other ways. Here, we will take the safest approach, and do things one step at a time. Select the face that is at the bottom of the hollow space we carved earlier inside the block. Create a new sketch, add a circle with a radius of 4.8825mm, import the left border of the face, and constrain it vertically and horizontally at 10.2mm from the upper corner of the face: If you have trouble to select features hiding part of the model can help. To hide a feature select it from tree view and press Space-key to toggle visibility. Leave edit mode, and pad this sketch with a distance of 12.6mm Create a linear pattern from this last pad, give it a length of 24mm and 3 occurrences. We now have three filled tubes filling the hollow space: Now let's make the final holes. Select the circular face of the first of our three "pins" Create a new sketch, import the circular border of our face, create a circle with a radius constraint of 3.6mm, and add a Point on Point Constraint between the center of the imported circle and our new circle. We now have a perfectly centered circle,and once again fully constrained: Leave edit mode, and create a pocket from this sketch, with a length of 12.6mm Create a linear pattern from this pocket, with a length of 24mm and 3 occurrences. That's the last step, our piece of lego is now complete, so we can give it a nice color to mark our victory! You will notice that our modeling history (what appears in the tree view) has become quite long. This is precious because every single step of what we did can be changed later on. Adapting this model for another kind of brick, for example one with 2x2 dots, instead of 2x4, would be a piece of cake, we would just need to change a couple of dimensions and the number of occurrences in linear patterns. We could as easily create bigger pieces that don't exist in the original Lego game. But we could also want to get rid of the history, for example if we are going to model a castle with this brick, and we don't want to have this whole history repeated 500 times in our file. There are two simple ways to get rid of the history, one is using the Create simple copy tool from the Part Workbench, which will create a copy of our piece that doesn't depend anymore on the history (you can delete the whole history afterwards), the other way is exporting the piece as a STEP file and reimporting it. Assembling But the best of both worlds also exists, which is the Assembly2 Workbench, an addon that can be installed from the FreeCAD-addons repository. This Workbench is named "2" because there is also an official built-in Assembly Workbench in development, which is not ready yet. The Assembly2 Workbench, however, already works very well to construct assemblies, and also features a couple of object-to-object constraints which you can use to constrain the position of one object in relation to another. In the example below, however, it will be quicker and easier to position the pieces using Draft Rotate than using the Assembly2 constraints. Save the file as it is now Install the Assembly2 Workbench and restart FreeCAD Create a new empty document Switch to the Assembly2 workbench Press the Import a part from another FreeCAD document button Select the file we saved above The final piece will be imported in the current document. The Assembly2 workbench will determine automatically what is the final piece in our file that needs to be used, and the new object stays linked to the file. If we go back and modify the contents of the first file, we can press the Update parts imported into the assembly button to update the pieces here. By using the Import a part from another FreeCAD document button several times, and moving and rotating the pieces (with the Draft tools or by manipulating their Placement property), we can quickly create a small assembly: Downloads The model produced during this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/lego.FCStd Read more The Sketcher The Part Design Workbench The Assembly2 Workbench


Manual:Traditional modeling, the CSG way

CSG stands for Constructive Solid Geometry and describes the most basic way to work with solid 3D geometry, which is creating complex objects by adding and removing pieces to/from solids by using Boolean operations such as union, subtraction or intersection. As we saw earlier in this manual, FreeCAD can handle many types of geometry, but the preferred and most useful type for the kind of 3D objects that we want to design with FreeCAD, that is, real-world objects, is, without a doubt, solid, BREP geometry, that is mainly handled by the Part Workbench. Unlike polygon meshes, which are made only of points and triangles, BREP objects have their faces defined by mathematical curves, which permits absolute precision, no matter the scale. The difference between the two can be compared to the difference between bitmap and vector images. As with bitmap images, polygon meshes have their curved surfaces divided into a series of points. If you look at it closely, or print it very large, you will see not a curved but a faceted surface. In both vector images and BREP data, the position of any point on a curve is not stored in the geometry but calculated on the fly, with exact precision. In FreeCAD, all BREP-based geometry is handled by another piece of open source software, OpenCasCade. The main interface between FreeCAD and the OpenCasCade kernel is the Part Workbench. Most other workbenches build their functionality on top of the Part Workbench. Although other workbenches often offer more advanced tools to build and manipulate geometry, since they all actually manipulate Part objects, it is very useful to know how these objects work internally, and be able to use the Part tools since, being more simple, they can very often help you to work around problems that the more intelligent tools fail to solve properly. To illustrate the working of the Part Workbench, we will model this table, using only CSG operations (except the screws, for which we will use one of the addons, and the dimensions, which will see in the next chapter): Let's create a new document (Ctrl+N or menu File → New Document) to hold our table design. The document is initially called "unnamed" in the Model tab in the Combo View panel, but if you save the document (Ctrl+Shift+S or menu File → Save As) as a new FreeCAD document called "table.FCStd" the document will be renamed "table", which more clearly identifies the project. Now we can switch to the Part Workbench and start to create our first table leg. Press the Cube button Select the Cube, then set the following properties (in the Data tab): Length: 80mm (or 8cm, or 0.8m, FreeCAD works in any unit) Width: 80mm Height: 75cm Duplicate the Cube by pressing Ctrl+C then Ctrl+V (or menu Edit → Copy and Paste) (No change will be evident, as the second object is overlaying the first.) Select the new object named Cube001 that has been created (Click on Cube001 in the left side Model tab) Change its position by editing its Placement property: Position x: 8mm Position y: 8mm You should obtain two high cubes, one 8mm apart from the other: Now we can subtract one from the other: Select the first one, that is, the one that will stay, then, with the CTRL key pressed, select the other one, that will be subtracted (the order is important) and press the Cut button: Observe that the newly created object, called "Cut", still contains the two cubes we used as operands. In fact, the two cubes are still there in the document, they have merely been hidden and grouped under the Cut object in the tree view. You can still select them by expanding the arrow next to the Cut object, and, if you wish, turn them visible again by right-clicking them or change any of their properties. You can use Cut -tool and other Boolean tools also through "Combo view" with Boolean. It gives more explicit but longer way to do it. Now let's create the three other feet by duplicating our base cube 6 other times. Since it is still copied, you can simply paste (Ctrl+V) 6 times. Change their position as follows: Cube002: x: 0, y: 80cm Cube003: x: 8mm, y: 79.2cm Cube004: x: 120cm, y: 0 Cube005: x: 119.2cm, y: 8mm Cube006: x: 120cm, y: 80cm Cube007: x: 119.2cm, y: 79.2cm Now let's do the three other cuts, selecting first the "host" cube then the cube to be cut off. We now have four Cut objects: You might have been thinking that, instead of duplicating the base cube six times, we could have duplicated the complete foot three times. This is totally true, as always in FreeCAD, there are many ways to achieve a same result. This is a precious thing to remember, because, as we will advance into more complex objects, some operations might not give the correct result and we often need to try other ways. We will now make holes for the screws, using the same Cut method. Since we need 8 holes, two in each foot, we could make 8 objects to be subtracted. Instead, let's explore other ways and make 4 tubes, that will be reused by two of the feet. So let's create four tubes by using the Cylinder tool. You can again, make only one and duplicate it afterwards. Give all cylinders a radius of 6mm. This time, we will need to rotate them, which is also done via the Placement property under the Data tab (Note: change the Axis property before setting the Angle, or the rotation will not be applied): Cylinder: height: 130cm, angle: 90°, axis: x:0,y:1,z:0, position: x:-10mm, y:40mm, z:72cm Cylinder001: height: 130cm, angle: 90°, axis: x:0,y:1,z:0, position: x:-10mm, y:84cm, z:72cm Cylinder002: height: 90cm, angle: 90°, axis: x:-1,y:0,z:0, position: x:40mm, y:-10mm, z:70cm Cylinder003: height: 90cm, angle: 90°, axis: x:-1,y:0,z:0, position: x:124cm, y:-10mm, z:70cm You will notice that the cylinders are a bit longer than needed. This is because, as in all solid-based 3D applications, boolean operations in FreeCAD are sometimes oversensitive to face-on-face situations and might fail. By doing this, we put ourselves on the safe side. Now let's do the subtractions. Select the first foot, then, with CTRL pressed, select one of the tubes that crosses it, press the Cut button. The hole will be done, and the tube hidden. Find it in the tree view by expanding the pierced foot. Select another foot pierced by this hidden tube, then repeat the operation, this time Ctrl+ selecting the tube in the tree view, as it is hidden in the 3D view (you can also make it visible again and select it in the 3D view). Repeat this for the other feet until each of them has its two holes: As you can see, each foot has become a quite long series of operations. All this stays parametric, and you can go change any parameter of any of the older operations anytime. In FreeCAD, we often refer to this pile as "modeling history", since it in fact carries all the history of the operations you did. Another particularity of FreeCAD is that the concept of 3D object and the concept of 3D operation tend to blend into one same thing. The Cut is at the same time an operation, and the 3D object resulting from this operation. In FreeCAD this is called a "feature", rather than object or operation. Now let's do the tabletop, it will be a simple block of wood, let's do it with another Box with length: 126cm, width: 86cm, height: 8cm, position: x: 10mm, y: 10mm, z, 67cm. In the View tab, you can give it a nice brownish, wood-like color by changing its Shape Color property: Notice that, although the legs are 8mm thick, we placed it 10mm away, leaving 2mm between them. This is not necessary, of course, it won't happen with the real table, but it is a common thing to do in that kind of "assembled" models, it helps people who look at the model to understand that these are independent parts, that will need to be attached together manually later. Now that our five pieces are complete, it is a good time to give them more proper names than "Cut015". By right-clicking the objects in the tree view (or pressing F2), you can rename them to something more meaningful to yourself or to another person who would open your file later. It is often said that simply giving proper names to your objects is much more important than the way you model them. We will now place some screws. There is nowadays an extremely useful addon developed by a member of the FreeCAD community, that you can find on the FreeCAD addons repository, called Fasteners, that makes the insertion of screws very easy. Installing additional workbenches is easy and described on the addons pages. Once you have installed the Fasteners Workbench and restarted FreeCAD, it will appear in the workbenches list, and we can switch to it. Adding a screw to one of our holes is done by first selecting the circular edge of our hole: Then we can press one of the screw buttons of the Fasteners Workbench, for example the EN 1665 Hexagon bolt with flanges, heavy series. The screw will be placed and aligned with our hole, and the diameter will automatically be selected to match the size of our hole. Sometimes the screw will be placed inverted, which we can correct by flipping its invert property. We can also set its offset to 2mm, to follow the same rule we used between the tabletop and the feet: Repeat this for all the holes, and our table is complete! The internal structure of Part objects As we saw above, it is possible in FreeCAD to select not only whole objects, but parts of them, such as the circular border of our screw hole. This is a good time to have a quick look at how Part objects are constructed internally. Every workbench that produces Part geometry will be based on these: Vertices: These are points (usually endpoints) on which all the rest is built. For example, a line has two vertices. Edges: the edges are linear geometry like lines, arcs, ellipses or NURBS curves. They usually have two vertices, but some special cases have only one (a closed circle for example). Wires: A wire is a sequence of edges connected by their endpoints. It can contain edges of any type, and it can be closed or not. Faces: Faces can be planar or curved, and can be formed by one closed wire, which forms the border of the face, or more than one, in case the face has holes. Shells: Shells are simply a group of faces connected by their edges. It can be open or closed. Solids: When a shell is tightly closed, that is, it has no "leak", it becomes a solid. Solids carry the notion of inside and outside. Many workbenches rely on this to make sure the objects they produce can be built in the real world. Compounds: Compounds are simply aggregates of other shapes, no matter their type, into a single shape. In the 3D view, you can select individual vertices, edges or faces. Selecting one of these also selects the whole object. A note about shared design You might look at the table above, and think its design is not good. The tightening of the feet with the tabletop is probably too weak. You might want to add reinforcing pieces, or simply you have other ideas to make it better. This is where sharing becomes interesting. You can download the file made during this exercise from the link below, and modify it to make it better. Then, if you share that improved file, others might be able to make it even better, or use your well-designed table in their projects. Your design might then give other ideas to other people, and maybe you will have helped a tiny bit to make a better world... Downloads The file produced in this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/table.FCStd Read more The Part Workbench The FreeCAD addons repository The Fasteners Workbench


Part Helix

GuiCommand model explains how commands should be documented. Browse Category:UnfinishedDocu to see more incomplete pages like this one. See Category:Command Reference for all commands.

Description

The Part Helix geometric primitive creates a helix shape, defined by a radius, a pitch, and a total height. A common usage for the helix primitive is for Sweep operation. This process works essentially the same in the PartDesign Additive pipe tool.

Usage

    Switch to the Part Workbench. The Create Primitives dialogue can be accessed several ways: Pressing the Primitives button located in the Part toolbar. Using the Part → Create primitives → Helix entry in the Part menu.

Parameter

Pitch:The pitch corresponds to the space between two consecutive "turns" of the helix measured along the main axis of the helix. Height: The height corresponds to the overall height of the helix measured along the main axis of the helix. Radius: The radius corresponds to the radius of the circle built by the helix by viewing the helix from the top or bottom. Angle: Per default the helix is built on a imaginary cylinder. With this option it is possible to build the helix on a imaginary cone. This angle corresponds to the angle of the cone. The value must be comprised between 0 and +90 deg. Right-handed or Left-handed: This parameter specifies the handedness of the helix.

Location

X: The main axis of the helix will be translated along the x axis of the value you indicate in this field. Y: The main axis of the helix will be translated along the y axis of the value you indicate in this field. Z: The main axis of the helix will be translated along the z axis of the value you indicate in this field. Direction: Per default the main axis of the helix is the z axis. Here you have the possibility to edit the main axis of the helix. If you select the parameter "user defined..." , you will be invited to indicate the main axis of the helix by entering the coordinates of its vector. 3D View: allows you select center in the 3D view

Options

Properties

Once you have created the helix you have the possibility to edit its parameters.
The parameters in this menu are similar to those described above.
Base
Placement: allows you to move or rotate the helix Angle:


PartDesign AdditivePipe

Description

Additive Pipe creates a solid in the active Body by sweeping one or more sketches (also referred to as cross-sections) along an open or closed path. If the Body already contains features, the additive pipe will be merged to them. On the left: cross-sections (A) and (B) to be swept along path (C); resulting Additive pipe on the right.

Usage

The example image above shows two different cross-section shapes. The text below will describe the procedure with a single shape only. This will achieve a part with the same cross-section along the whole path.
    Create two separate sketches; one for the path, e.g two lines connected by a curve as in the image above, one for the cross-section shape, e.g. a circle as the first shape in the image above. Instead of a sketch also the face of a 3D object can be used. (introduced in version 0.20) Arrange the two shapes in 3D correctly. It is recommended to place the origin of the cross-section onto the line of the path. The two sketches should in most cases be orthogonal. This can be done with the 'Map Mode' function (make both sketches visible with Space. Select the cross-section sketch. Select Properties/DataTab/MapMode. Click the appearing ... button at the right side. In the Attachment Dialog select a vertex of the path sketch and select the correct mode to get the two sketches aligned correctly). Press the Additive pipe button. In the Select feature dialog, select either a sketch or a the face of a 3D object (introduced in version 0.20) to be used cross-section and click OK. Alternatively, the cross-section sketch or face can be selected prior to pressing the Additive pipe button. In that case you will not get a "Select feature' dialog. In the Pipe parameters under Path to sweep along, press the Object button. Select the sketch to be used as path in the 3D view. In this case the whole sketch will be used as path. Alternatively, single edges of the sketch can be selected by pressing Add Edge and selecting edges in the 3D view. Note that you must press the Add Edge for each edge again. You must select a continous line with no branches. The other settings should work with the default settings in most cases. Click OK.
To use more than one cross-section, start with the first cross-section sketch as described above. Then under Section transformation set the Transform mode to Multisection; press Add Section then select a sketch in the 3D view. Repeat for each additional cross-section.

Options

Section Transformation: Select Constant to use a single profile Select Multisection to use multiple profiles Section Orientation: Standard This keeps the cross section shape perpendicular to the path. This is the default setting. Fixed Orientation set by first profile and constant throughout. This deactivates the alignment to the path normal vector. That means that the cross-section shape will not rotate with the path. Sweep along a circle to see the effect. Frenet Create minimum possible twisting of profile. For more info, see Frenet-Serret Formulas Auxiliary Specify secondary path to guide pipe. For each point P along the sweep path, there will be a corresponding point Q on the auxiliary path. As the profile is swept, it will be transformed such that the PQ line is the normal of the sweep path. If Curvilinear is set, then the Q points are scaled proportionally along the sweep path, regardless of it's length. Binormal Specify binormal vector in X, Y and Z Corner Transition Transformed Right Rounded

Properties

DataLabel: name given to the operation, this name can be changed at convenience. DataRefine: true or false. If set to true, cleans the solid from residual edges left by features. See Part RefineShape for more details. DataSections: lists the sections used. DataSpine Tangent: true or false (default). True extends the path to include tangent edges. DataAuxiliary Spine Tangent: true or false (default). True extends the auxiliary path to include tangent edges. DataAuxiliary Curvelinear: true or false (default). True calculates normal between equidistant points on both spines. DataMode: profile mode. See Options. DataBinormal: binormal vector for corresponding orientation mode. DataTransition: transition mode. Options are Transformed, Right Corner or Round Corner. DataTransformation: Constant uses a single cross-section. Multisection uses two or more cross-sections. Linear, S-shape and Interpolation are currently not functional.

Limitations

Sketches used for cross-sections must form closed profiles. The path can only be from a single sketch, feature or ShapeBinder. In case you want to sweep along several edges from different sketches, use a SubShapeBinder. The path must not contain branches or T-junctions etc. Loops are allowed. It is not possible to use a vertex as cross-section. It can lead to issues if the cross-section is not perpendicular to the path in 3D (some other CAD systems consider the origin of the cross-section as the path and do not require to place that sketch explicitly). A cross-section cannot lie on the same plane as the one immediately preceding it. To better control the shape of the pipe, it is recommended that all the cross-sections have the same number of segments. For example, for a pipe between a rectangle and a circle, the circle may be broken down into 4 connected arcs. The cross-sections must not contain disjoint or crossing loops.


Part Sweep

Description

The Part Sweep tool is used to create a face, a shell, or a solid shape from one or more profiles (cross-sections) projected along a path. The Part Sweep tool is similar to Part Loft with the addition of a path to define the projection between profiles. A solid sweep generated from a single profile (A) projected along a path (B).

Usage

    Press the Sweep button. This opens the Sweep parameters in the Task panel. In the Available Profiles left column (previously Vertex/Edge/Wire/Face in v0.16), click on the element to be used as sweep profile, then click on the right arrow to place it in the Selected profiles right column (previously Sweep in v0.16). Repeat if more than one profile is desired. Use the up and down arrows to reorder the selected profiles. Click on the Sweep Path button, then choose either mode of selection: Single segment selection: select one or more contiguous edges in the 3D view (press CTRL for multiple selection) and click Done. The sweep will only be generated along the selected edges. Complete path selection: switch to the Model tab, select the 2D object to be used as path in the tree, switch back to the Task panel and click Done. The sweep will be generated along all the contiguous edges found in the 2D object. Define options Solid and Frenet. Click OK

Accepted geometry

Profiles: can be a point (vertex), line (Edge), wire or face. Edges and wires may be either open or closed. There are various profile limitations and complications, see below, however the profiles may come from the Part Workbench primitives, Draft Workbench features and Sketches. Path: can be a line (Edge) or series of connecting lines, wire or various Part Workbench primitives, Draft Workbench features or a Sketch. The path is often selected directly from the main model window, however it can also be selected from the Tree view (Model Tab of Combo View). The path can either be an entire appropriate shape or an appropriate sub-component of a more advance shape (for example, an edge of a Part Cube could be selected as the path). The path may be either open or closed and will thus create either an open or closed Sweep. A closed path such as a Part Circle will result in a closed Sweep. For example a Sweep of a smaller circle around a path of a larger circle will create a torus.

Properties

Solid

If "Solid" is set to "true", FreeCAD creates a solid, provided the profiles are of closed geometry; if set to "false", FreeCAD creates a face or (if more than one face) a shell for either open or closed profiles.

Frenet

The "Frenet" property controls how the profile orientation changes as it follows along the sweep path. If "Frenet" is "false", the orientation of the profile is kept consistent from point to point. The resulting shape has the minimum possible twisting. Unintuitively, when a profile is swept along a helix, this results in the orientation of the profile slowly creep (rotate) as it follows the helix. Setting "Frenet" to true prevents such a creep. If "Frenet" is "true" the orientation of the profile is computed basing on local curvature and tangency vectors of the path. This keeps the orientation of the profile consistent when sweeping along a helix (because curvature vector of a straight helix is always pointing to its axis). However, when path is not a helix, the resulting shape can have strange looking twists sometimes. For more information, see Frenet Serret formulas.

Transition

"Transition" sets the transition style of the Sweep at a joint in the path, if the path does not define the corner transition (for example where the path is a wire). The property is not exposed in the Task panel and can be found in properties after the Sweep has been created.

Profile limitations and complications

A vertex or point vertex or point may only be used as the first and/or last profile in the list of profiles. For example you can not Sweep from a circle to a point, to a ellipse. However you could Sweep from a point to a circle to an ellipse to another point. Open or closed geometry profiles can not be mixed in one single Sweep In one Sweep, all profiles (lines wires etc.) must be either open or closed. For example FreeCAD can not Sweep between one Part Circle and one default Part Line. Draft Workbench features Draft Workbench features can be directly used as a profile in FreeCAD 0.14 or later. For example the following Draft features can be used as profiles in a Part Sweep Draft Polygon. Draft Point, Line, wire, Draft B-spline, Bezier Curve Draft Circle, Ellipse, Rectangle PartDesign Sketches The profile may be created with a sketch. However only a valid sketch will be shown in the list to be available for selection. The sketch must contain only one open or closed wire or line (can be multiple lines, if those lines are all connected as they are then a single wire) Part Workbench the profile can be a valid Part geometric primitive which can be created with the Part Primitives tool For example the following Part geometric primitives can be a valid profile Point (Vertex), Line (Edge) Helix, Spiral Circle, Ellipse Regular Polygon Plane (Face)

Links

Since Sweep is often used to create threads for screws, you should see Thread for Screw Tutorial.


Part Fuse

Description

The Part Fuse tool fuses (unites) selected Part objects into one. This operation is fully parametric and the components can be modified and the result recomputed. Note: This command is an automated form of the Boolean operation.

Usage

    Select two or more shapes There are several ways to invoke the command: Press the Part Fuse button in the Part tools toolbar Use the Part → Boolean → Union entry in the Part menu

Supported inputs

Input objects must be OpenCASCADE shapes. Examples: stuff made with Part, PartDesign, Sketcher workbenches. Not meshes (unless those were converted to shapes) - for meshes, there are specific Boolean tools in MeshDesign workbench. Solid + Solid: the result is a solid that occupies all the volume covered by the inputs Shell + Shell, Shell + Face, Face + Face: the result is a shell. Where faces intersect, they are split. Shells can be non-manifold. After fusion, faces can be united by Refining the result. Wire + Wire, Edge + Wire, Edge + Edge: the result is a wire. Edges are split where they intersect. Compounds are supported; however, it is assumed that shapes packed into a compound do not touch or intersect. If they actually do, Fusion will likely fail, or produce an incorrect result.

Options

Items can be added and removed from the fusion, by dragging them in or out of the fusion feature in the tree view with the mouse. A manual recompute (press F5 key or click on the Refresh/Recompute icon) is required to see the results. After this operation is complete, it may be necessary to clean up the shape with RefineShape.


Part Cut

Description

Cuts (subtracts) selected Part objects, the last one being subtracted from the first one. This operation is fully parametric and the components can be modified and the result recomputed. Note: This command is an automated form of the Boolean operation.

Usage

    Select two shapes Invoke the Part Cut command several ways: Press the Cut button in the Part toolbar Use the Part → Boolean → Cut entry from the Part menu

Supported inputs

Input objects must be OpenCASCADE shapes. Examples: stuff made with Part, PartDesign, Sketcher workbenches. Not meshes (unless those were converted to shapes) - for meshes, there are specific Boolean tools in MeshDesign workbench.


Manual:Traditional 2D drafting

You might be interested by FreeCAD because you already have some technical drawing experience, for example with software like AutoCAD. Or you already know something about design, or you prefer to draw things before building them. In any case, FreeCAD features a more traditional workbench, with tools found in most 2D CAD applications: The Draft Workbench. The Draft Workbench, although it adopts ways of working inherited from the traditional 2D CAD world, is not limited at all to the 2D realm. All its tools work in the whole 3D space and many of the Draft tools, for example Rotate, are commonly used all over FreeCAD because they are often more intuitive than changing placement parameters manually. Among the tools offered by the Draft Workbench, you will find traditional drawing tools like Offset, a working plane/grid system that allows you to define precisely in which plane you are working, and a complete snapping system that makes it very easy to draw and position elements precisely in relation to each other. To showcase the workflow and possibilities of the Draft Workbench, we will walk through a simple exercise, the result of which will be this little drawing, showing the floor plan of a small house that contains only a kitchen top (A pretty absurd floor plan, but we can do what we want here, can't we?): Switch to the Draft Workbench As in all technical drawing applications, it is wise to set up your environment correctly, it will save you a lot of time. Configure the grid and working plane, Text and Dimension settings to your liking in menu Edit → Preferences → Draft. In this exercise, however, we will act as if these settings were left at their default values. One option might need your attention, though: the "Fill objects with faces whenever possible" option. If this is marked, closed objects like rectangles or circles will be filled with a face by default, which can make snapping to underlying objects difficult. You can either turn this option off now, or, later on, turn the "Make Face" property of each individual object off, to prevent them from creating a face. The Draft Workbench also has two special toolbars: One with visual settings, where you can change the current working plane, turn construction mode on/off, set the line color, face color, line weight and text size to be used for new objects, and another one with snap locations. There, you can turn the grid on/off and set/unset individual Snap locations: Turning on all the snap buttons is convenient, but also makes drawing slower, as more calculation needs to be done when you move the mouse cursor. It is often better to keep only the ones you will actually use. Let's start by turning construction mode on, which will allow us to draw some guidelines on which we will draw our final geometry. If you wish, set the working plane to XY. If you do this, the working plane won't change, no matter the current view. If not, the working plane will adapt automatically to the current view, and you should take care of staying in top view whenever you want to draw on the XY (ground) plane. Then, select the Rectangle tool and draw a rectangle, starting at point (0,0,0), of 2 meters by 2 meters (leave the Z at zero). Note that most of the Draft commands can be fully performed from the keyboard, without touching the mouse, using their two-letter shortcut. Our first 2x2m rectangle can be done like this: re 0 Enter 0 Enter 0 Enter 2m Enter 2m Enter 0 Enter. Duplicate that rectangle by 15cm inside, using the Offset tool, turning its Copy mode on, and giving it a distance of 15cm: We can then draw a couple of vertical lines to define where our doors and windows will be placed, using the Line tool (note that the "relative" mode box should be unchecked for this step). The crossing of these lines with our two rectangles will give us useful intersections to snap our walls to. Draw the first line from point (15cm, 1m, 0) to point (15cm, 3m, 0). Duplicate that line 5 times, using the Move tool with Copy mode turned on. Turn also the Relative mode on, which will allow us to define movements in relative distances, which is easier than calculating the exact position of each line. Perform each move operation in sequence on the line that was created immediately prior. Give each new copy any start point, you can leave it at (0,0,0) for example, and the following relative endpoints: line001: x: 10cm line002: x: 120cm line003: x: -55cm, y: -2m line004: x: 80cm line005: x: 15cm That is all we need now, so we can switch construction mode off. Check that all the construction geometry has been placed into a "Construction" group, which makes it easy to hide it all at once or even delete it completely later on. Now let's draw our two wall pieces using the Wire tool. Make sure the intersection snap is turned on, as we will need to snap to the intersections of our lines and rectangles. Draw two wires as follows, by clicking all the points of their contours. To close them, either click on the first point again, or press the Close button: We can change their default grey color to a nice hatch pattern, by selecting both walls, then setting their Pattern property to Simple, and their Pattern size to your liking, for example 0.005. We can now hide the construction geometry by right-clicking the Construction group and choose Hide Selection. Let's now draw the windows and doors. Make sure the midpoint snap is turned on, and draw six lines as follow: We will now change the door line to create an opened door symbol. Start by rotating the line using the Rotate tool. Click the endpoint of the line as rotation center, give it a start angle of 0, and an end angle of -90. Then create the opening arc with the Arc tool. Pick the same point as the rotation center we used in the previous step as center, click the other point of the line to give the radius, then the start and end points as follow: We can now start placing some furniture. To begin with, let's place a counter by drawing a rectangle from the upper left inner corner, and giving it a width of 170cm and a height of -60cm. In the image below, the Transparency property of the rectangle is set to 80%, to give it a nice furniture look. Then let's add a sink and a cookertop. Drawing these kinds of symbols by hand can be very tedious, and they are usually easy to find on the internet, for example on http://www.cad-blocks.net . In the Downloads section below, for convenience, we separated a sink and a cookertop from this project, and saved them as DXF files.You can download these two files by visiting the links below, and right-clicking the Raw button, then choosing save as. Inserting a DXF file into an opened FreeCAD document can be done either by choosing the File → Import menu option, or by dragging and dropping the DXF file from your file explorer into the FreeCAD window. The contents of the DXF files might not appear right on the center of your current view, depending on where they were in the DXF file. You can use menu View → Standard views → Fit all to zoom out and find the imported objects. Insert the two DXF files, and move them to a suitable location on the tabletop: We can now place a couple of dimensions using the Dimension tool. Dimensions are drawn by clicking 3 points: the start point, an end point, and a third point to place the dimension line. To make horizontal or vertical dimensions, even if the two first points are not aligned, press Shift while clicking the second point. You can change the position of a dimension text by double-clicking the dimension in the tree view. A control point will allow you to move the text graphically. In our exercise, the "0.15" texts have been moved away for better clarity. You can change the contents of the dimension text by editing their Override property. In our example, the texts of the door and window dimensions have been edited to indicate their heights: Let's add some description texts using the Text tool. Click a point to position the text, then enter the lines of text, pressing Enter after each line. To finish, press Enter twice. The indication lines (also called "leaders") that link the texts to the item they are describing are simply done with the Wire tool. Draw wires, starting from the text position, to the place being described. Once that is done, you can add a bullet or arrow at the end of the wires by setting their End Arrow property to true Our drawing is now complete! Since there are quite a number of objects there, it would be wise do some cleaning and restructure everything into nice groups, to make the file easier to understand for other people: We can now print our work by placing it on a Drawing sheet, which we will show later in this manual, or directly export our drawing to other CAD applications, by exporting it to a DXF file. Simply select our "Floor plan" group, select menu File → Export, and select the Autodesk DXF format. The file can then be opened in any other 2D CAD application such as LibreCAD. You might notice some differences, depending on the configurations of each application. The most important thing about the Draft Workbench, however, is that the geometry you create with it can be used as a base or easily extruded into 3D objects, simply by using the Trimex (Trim/Extend/Extrude) tool, which under the hood performs a Part Extrusion, but does it "the Draft way", that is, allows you to indicate and snap the extrusion length graphically. Experiment extruding our walls as shown below. By pressing the working plane button after selecting a face of an object, you are also able to place the working plane anywhere, and therefore draw Draft objects in different planes, for example on top of the walls. These can then be extruded to form other 3D solids. Experiment setting the working plane on one of the top faces of the walls, then draw some rectangles up there. All kinds of openings can also be done as easily by drawing Draft objects on the faces of walls, then extruding them, then using the boolean tools from the Part Workbench to subtract them from another solid, as we saw in the previous chapter. Fundamentally, what the Draft Workbench does is to provide graphical ways to create basic Part operations. While in Part you will usually position objects by setting their placement parameter, in Draft you can do it on-screen. There are times when one is better, other times when the other is preferable. Don't forget, you can create custom toolbars in one of these workbenches, add the tools from the other, and get the best of both worlds.

Downloads

The file created during this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/cabin.FCStd The sink DXF file: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/sink.dxf The cookertop DXF file: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/cooktop.dxf The final DXF file produced during this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/cabin.dxf

Related

The Draft Workbench Snapping The Draft working plane


Draft Workbench

Introduction

The Draft Workbench is primarily focused on the creation and modification of 2D objects in FreeCAD. But it is not restricted to the XY plane of the global coordinate system. Its objects can have any orientation and position in 3D space, and some Draft objects can either be planar or non-planar. Draft objects can be used for general drafting, similar to what can be done with Inkscape or AutoCAD. But they can also form the base for the creation of 3D objects in other workbenches. A Draft Wire may define the path of an Arch Wall, a Draft Polygon can be extruded with Part Extrude, etc. Many of the Draft modifier tools can be applied to 2D and 3D objects created with other workbenches as well. You can, for example, move a Sketch or create a Draft OrthoArray from a Part object. The Draft Workbench also provides tools to define a working plane, a grid, and a snapping system to precisely control the position of geometry. If your primary goal is the production of complex 2D drawings and DXF files, and you don't need 3D modelling, FreeCAD may not be the right choice for you. You may wish to consider a dedicated software program for technical drafting instead, such as LibreCAD or QCad. The image shows the grid aligned with the XY plane.
On the left, in white, several planar objects.
On the right a non-planar Draft Wire used as the Path Object of a Draft PathArray.

Drafting

Line: creates a straight line. Polyline: creates a polyline, a sequence of several connected line segments. Fillet: creates a fillet, a rounded corner, or a chamfer, a straight edge, between two Draft Lines. introduced in version 0.19 Arc tools Arc: creates a circular arc from a center, a radius, a start angle and an aperture angle. Arc by 3 points: creates a circular arc from three points that define its circumference. introduced in version 0.19 Circle: creates a circle from a center and a radius. Ellipse: creates an ellipse from two points defining a rectangle in which the ellipse will fit. Rectangle: creates a rectangle from two points. Polygon: creates a regular polygon from a center and a radius. B-spline: creates a B-spline curve from several points. Bézier tools Cubic Bézier curve: creates a Bézier curve of the third degree. introduced in version 0.19 Bézier curve: creates a Bézier curve from several points. Point: creates a simple point. Facebinder: creates a surface object from selected faces. ShapeString: creates a compound shape that represents a text string. Hatch: creates hatches on the planar faces of a selected object. introduced in version 0.20

Annotation

Text: creates a multi-line text at a given point. Dimension: creates a linear dimension, a radial dimension or an angular dimension. Label: creates a multi-line text with a 2-segment leader line and an arrow. Annotation styles...: allows you to define styles that affect the visual properties of annotation-like objects. introduced in version 0.19

Modification

Move: moves or copies selected objects from one point to another. Rotate: rotates or copies selected objects around a center point by a given angle. Scale: scales or copies selected objects around a base point. Mirror: creates mirrored copies from selected objects. Offset: offsets each segment of a selected object over a given distance, or creates an offset copy of the selected object. Trimex: trims or extends a selected object. Stretch: stretches objects by moving selected points. Clone: creates linked copies, clones, of selected objects. Array tools Array: creates an orthogonal array from a selected object. It can optionally create a Link array. introduced in version 0.19 Polar array: creates an array from a selected object by placing copies along a circumference. It can optionally create a Link array. introduced in version 0.19 Circular array: creates an array from a selected object by placing copies along concentric circumferences. It can optionally create a Link array. introduced in version 0.19 Path array: creates an array from a selected object by placing copies along a path. Path Link array: idem, but create a Link array instead of a regular array. introduced in version 0.19 Point Array: creates an array from a selected object by placing copies at the points from a point compound. Point Link array: idem, but create a Link array instead of a regular array. introduced in version 0.19 Edit: puts selected objects in Draft Edit mode. In this mode the properties of objects can be edited graphically. Subelement highlight: temporarily highlights selected objects, or the base objects of selected objects. Join: joins Draft Lines and Draft Wires into a single wire. Split: splits a Draft Line or Draft Wire at a specified point or edge. Upgrade: upgrades selected objects. Downgrade: downgrades selected objects. Wire to B-spline: converts Draft Wires to Draft BSplines and vice versa. Draft to Sketch: converts Draft objects to Sketcher Sketches and vice versa. Set slope: slopes selected Draft Lines or Draft Wires by increasing, or decreasing, the Z coordinate of all points after the first one. Flip dimension: rotates the dimension text of selected Draft Dimensions 180° around the dimension line. Shape 2D view: creates 2D projections from selected objects.

Draft Tray

The Draft Tray allows selecting the working plane, defining style settings, toggling construction mode, and specifying the active layer or group. Select Plane: selects the current Draft working plane. Also available in the menu: Draft → Utilities → Select Plane. Set style: sets the default style for new objects. Also available in the menu: Draft → Utilities → Set style. introduced in version 0.19 Toggle construction mode: switches Draft construction mode on or off. Also available in the menu: Draft → Utilities → Toggle construction mode. AutoGroup: changes the active Draft Layer or, optionally, the active Std Group or group-like Arch object.

Draft annotation scale widget

With the Draft annotation scale widget the Draft annotation scale can be specified. introduced in version 0.19

Draft snap widget

The Draft snap widget can be used as an alternative for the Draft Snap toolbar. introduced in version 0.19

Draft Snap toolbar

The Draft Snap toolbar allows selecting the active snap options. The buttons belonging to active options stay depressed. For general information about snapping see: Draft Snap. Snap Lock: enables or disables snapping globally. Snap Endpoint: snaps to the endpoints of edges. Snap Midpoint: snaps to the midpoint of straight and circular edges. Snap Center: snaps to the center point of faces and circular edges, and to the DataPlacement point of Draft WorkingPlaneProxies and Arch BuildingParts. Snap Angle: snaps to the special cardinal points on circular edges, at multiples of 30° and 45°. Snap Intersection: snaps to the intersection of two edges. Snap Perpendicular: snaps to the perpendicular point on edges. Snap Extension: snaps to an imaginary line that extends beyond the endpoints of straight edges. Snap Parallel: snaps to an imaginary line parallel to straight edges. Snap Special: snaps to special points defined by the object. Snap Near: snaps to the nearest point on faces or edges. Snap Ortho: snaps to imaginary lines that cross the previous point at 0°, 45°, 90° and 135°. Snap Grid: snaps to the intersections of grid lines. Snap WorkingPlane: projects the snap point onto the current working plane. Snap Dimensions: shows temporary X and Y dimensions. Toggle Grid: switches the grid on or off.

Draft utility tools toolbar

Layer: creates a Draft Layer. introduced in version 0.19 Add a new named group: creates a named Std Group and moves selected objects to that group. introduced in version 0.20 Move to group...: moves objects to a Std Group. It can also ungroup objects. Select group: selects the content of Draft Layers, Std Groups or group-like Arch objects. Add to Construction group: moves objects to the Draft construction group. Toggle normal/wireframe display: switches the ViewDisplay Mode property of selected objects between Flat Lines and Wireframe. Create working plane proxy: creates a working plane proxy to save the current Draft working plane.

Additional tools

The Draft → Utilities menu contains several tools. Most of them can also be accessed from toolbars or the Draft Tray and have already been mentioned above. For the following tools this is not the case: Apply current style: applies the current style settings to selected objects. Heal: heals problematic Draft objects found in very old files. Toggle continue mode: switches continue mode on or off. Show snap toolbar: shows the Draft Snap toolbar.

Additional features

Working plane: the plane in the 3D view where new Draft objects are created. Snapping: select exact geometric points on, or defined by, existing objects or the grid. Constraining: for each subsequent point you can constrain the movement of the cursor to the X, Y, or Z direction. Construction mode: places new Draft objects in a dedicated group making it easier to hide or delete them. Pattern: Draft objects with a DataMake Face property can display an SVG pattern instead of a solid face color.

Tree view context menu

The following additional options are available in the Tree view context menu:

Default options

If there is an active document the context menu contains one additional sub-menu: Utilities: a subset of the tools available in the main Draft Utilities menu.

Wire options

For a Draft Wire, Draft BSpline, Draft CubicBezCurve and Draft BezCurve this additional option is available: Flatten this wire: flattens the wire based on its internal geometry. This option currently does not work properly.

Layer container options

For a Draft LayerContainer these additional options are available: Merge layer duplicates: merges all layers with the same base label. This does not work in FreeCAD version 0.19. Add new layer: adds a new layer to the current document.

Layer options

For a Draft Layer these additional options are available: Activate this layer: activates the selected layer. Select layer contents: selects the objects inside the selected layer.

Working plane proxy options

For a Draft WorkingPlaneProxy these additional options are available: Write camera position: updates the ViewView Data property of the working plane proxy with the current 3D view camera settings. Write objects state: updates the ViewVisibility Map property of the working plane proxy with the current visibility state of objects in the document.

3D view context menu

The following additional options are available in the 3D view context menu:

Default options

If there is an active document the context menu contains one additional sub-menu: Utilities: a subset of the tools available in the main Draft Utilities menu.

Obsolete tools

These commands are obsolete but still available: Array: creates an orthogonal array from a selected object. The created array can be turned into a polar array or a circular array by changing its DataArray Type property. obsolete in version 0.19 Drawing: inserts views of selected objects into a drawing page. obsolete in version 0.17

Preferences

Preferences: general preferences for the Draft Workbench. Import Export Preferences: preferences available for importing from and exporting to different file formats.

File formats

The Draft Workbench provides FreeCAD with importers and exporters for several file formats. These are used by the Std Import and Std Export commands. Autodesk .DXF: imports and exports Drawing Exchange Format files. See also FreeCAD and DXF Import. Autodesk .DWG: imports and exports DWG files via an external DWG converter. See also FreeCAD and DWG Import. Scalable Vector Graphics .SVG: imports and exports Scalable Vector Graphics files. Open Cad format .OCA: imports and exports OCA/GCAD files. Airfoil Data Format .DAT: imports DAT files describing Airfoil profiles.

Unit tests

See also: Test Workbench. To run the unit tests of the workbench execute the following from the operating system terminal: freecad -t TestDraft

Scripting

See also: Autogenerated API documentation and FreeCAD Scripting Basics. The workbench includes a module to create samples of all objects in a new document. introduced in version 0.19 Use this to test that all objects are produced correctly: import drafttests.draft_test_objects as dto doc = dto.create_test_file() Inspecting the code of this module can help to understand the programming interface.

Tutorials

Draft tutorial Draft ShapeString tutorial


Sketcher Workbench

Introduction

The FreeCAD Arch Workbench, and other workbenches. Generally, a 2D drawing is considered the starting point for most CAD models, as a 2D sketch can be "extruded" to create a 3D shape; further 2D sketches can be used to create other features like pockets, ridges, or extrusions on top of the previously built 3D shapes. Together with boolean operations defined in the Part Workbench, the Sketcher forms the basis of the constructive solid geometry (CSG) method of building solids. Moreover, together with the PartDesign Workbench operations, the Sketcher also forms the basis of the feature editing methodology of creating solids. The Sketcher workbench features "constraints", allowing 2D shapes to follow precise geometrical definitions in terms of length, angles, and relationships (horizontality, verticality, perpendicularity, etc.). A constraint solver calculates the constrained-extent of 2D geometry and allows interactive exploration of degrees-of-freedom of the sketch. A fully constrained sketch

Basics of constraint sketching

To explain how the Sketcher works, it may be useful to compare it to the "traditional" way of drafting.

Traditional Drafting

The traditional way of CAD drafting inherits from the old drawing board. Orthogonal (2D) views are drawn manually and intended for producing technical drawings (also known as blueprints). Objects are drawn precisely to the intended size or dimension. If you want to draw an horizontal line 100mm in length starting at (0,0), you activate the line tool, either click on the screen or input the (0,0) coordinates for the first point, then make a second click or input the second point coordinates at (100,0). Or you will draw your line without regard to its position, and move it afterwards. When you've finished drawing your geometries, you add dimensions to them.

Constraint Sketching

The Sketcher moves away from this logic. Objects do not need to be drawn exactly as you intend to, because they will be defined later on by constraints. Objects can be drawn loosely, and as long as they are unconstrained, can be modified. They are in effect "floating" and can be moved, stretched, rotated, scaled, and so on. This gives great flexibility in the design process.

What are constraints?

Instead of dimensions, Constraints are used to limit the degrees of freedom of an object. For example, a line without constraints has 4 Degrees Of Freedom (abbreviated as "DOF"): it can be moved horizontally or vertically, it can be stretched, and it can be rotated. Applying a horizontal or vertical constraint, or an angle constraint (relative to another line or to one of the axes), will limit its capacity to rotate, thus leaving it with 3 degrees of freedom. Locking one of its points in relation to the origin will remove another 2 degrees of freedom. And applying a dimension constraint will remove the last degree of freedom. The line is then considered fully-constrained. Multiple objects can be constrained between one another. Two lines can be joined through one of their points with the coincident point constraint. An angle can be set between them, or they can be set perpendicular. A line can be tangent to an arc or a circle, and so on. A complex Sketch with multiple objects will have a number of different solutions, and making it fully-constrained means that just one of these possible solutions has been reached based on the applied constraints. There are two kinds of constraints: geometric and dimensional. They are detailed in the 'Tools' section below.

What the Sketcher is not good for

The Sketcher is not intended for producing 2D blueprints. Once sketches are used to generate a solid feature, they are automatically hidden. Constraints are only visible in Sketch edit mode. If you only need to produce 2D views for print, and don't want to create 3D models, check out the Draft workbench. Unlike Sketcher elements, Draft objects don't use constraints; they are simple shapes defined at the moment of creation. Both Draft and Sketcher can be used for 2D geometry drawing, and 3D solid creation, although their preferred use is different; the Sketcher is normally used together with Part and PartDesign to create solids; Draft is normally used for simple planar drawings over a grid, as when drawing an architectural floor plan; in these situations Draft is mostly used together with the Arch Workbench. The tool Draft2Sketch converts a Draft object to a Sketch object, and vice versa; many tools that require a 2D element as input work with either type of object as an internal conversion is done automatically.

Sketching Workflow

A Sketch is always 2-dimensional (2D). To create a solid, a 2D Sketch of a single enclosed area is created and then either Padded or Revolved to add the 3rd dimension, creating a 3D solid from the 2D Sketch. If a Sketch has segments that cross one another, places where a Point is not directly on a segment, or places where there are gaps between endpoints of adjacent segments, Pad or Revolve won't create a solid. Sometimes a Sketch which contains lines which cross one another will work for a simple operation such as Pad, but later operations such as Linear Pattern will fail. It is best to avoid crossing lines. The exception to this rule is that it doesn't apply to Construction (blue) Geometry. Inside the enclosed area we can have smaller non-overlapping areas. These will become voids when the 3D solid is created. Once a Sketch is fully constrained, the Sketch features will turn green; Construction Geometry will remain blue. It is usually "finished" at this point and suitable for use in creating a 3D solid. However, once the Sketch dialog is closed it may be worthwhile going to Check geometry to ensure there are no features in the Sketch which may cause later problems.

Tools

The Sketcher Workbench tools are all located in the Sketch menu that appears when you load the Sketcher Workbench.

General

New sketch: Creates‎ a new sketch on a selected face or plane. If no face is selected while this tool is executed the user is prompted to select a plane from a pop-up window. Edit sketch: Edit the selected Sketch. This will open the Sketcher Dialog. Leave sketch: Leave the Sketch editing mode. View sketch: Sets the model view perpendicular to the sketch plane. View section: Creates a section plane that temporarily hides any matter in front of the sketch plane. Map sketch to face: Maps a sketch to the previously selected face of a solid. Reorient sketch: Allows you to attach the sketch to one of the main planes. Validate sketch: Verify the tolerance of different points and adjust them. Merge sketches: Merge two or more sketches. Mirror sketch: Mirror a sketch along the x-axis, the y-axis or the origin. Stop operation: When in edit mode, stop the current operation, whether that is drawing, setting constraints, etc.

Sketcher geometries

These are tools for creating objects. Point: Draws a point. Line: Draws a line segment between 2 points. Lines are infinite regarding certain constraints. Create an arc: This is an icon menu in the Sketcher toolbar that holds the following commands: Arc: Draws an arc segment from center, radius, start angle and end angle. Arc by 3 points: Draws an arc segment from two endpoints and another point on the circumference. Create a circle: This is an icon menu in the Sketcher toolbar that holds the following commands: Circle: Draws a circle from center and radius. Circle by 3 points: Draws a circle from three points on the circumference. Create a conic: The sketcher provides the following conical sections. Unlike B-splines they can be used with all sorts of constraints such as Tangent, Point On Object, or Perpendicular. Ellipse by center: Draws an ellipse by center point, major radius point and minor radius point. Ellipse by 3 points: Draws an ellipse by major diameter (2 points) and minor radius point. Arc of ellipse: Draws an arc of ellipse by center point, major radius point, starting point and ending point. Arc of hyperbola: Draws an arc of hyperbola. Arc of parabola: Draws an arc of parabola. Create a B-spline: This is an icon menu in the Sketcher toolbar that holds the following commands: Create B-spline: Draws a B-spline curve by its control points. Create periodic B-spline: Draws a periodic (closed) B-spline curve by its control points. Polyline (multiple-point line): Draws a line made of multiple line segments. Pressing the M key while drawing a Polyline toggles between the different polyline modes. Create rectangles: This is an icon menu in the Sketcher toolbar that holds the following commands: introduced in version 0.20 Rectangle: Draws a rectangle from 2 opposite points. Centered Rectangle: Draws a rectangle from a central point and an edge point. introduced in version 0.20 Rounded Rectangle: Draws a rounded rectangle from 2 opposite points. introduced in version 0.20 Create regular polygon: This is an icon menu in the Sketcher toolbar that holds the following commands: Triangle: Draws a regular triangle inscribed in a construction geometry circle. Square: Draws a regular square inscribed in a construction geometry circle. Pentagon: Draws a regular pentagon inscribed in a construction geometry circle. Hexagon: Draws a regular hexagon inscribed in a construction geometry circle. Heptagon: Draws a regular heptagon inscribed in a construction geometry circle. Octagon: Draws a regular octagon inscribed in a construction geometry circle. Create Regular Polygon : Draws a regular polygon by selecting the number of sides and picking two points: the center and one corner. Slot: Draws an oval by selecting the center of one semicircle and an endpoint of the other semicircle. Fillet: Makes a fillet between two lines joined at one point. Select both lines or click on the corner point, then activate the tool. Trimming: Trims a line, circle or arc with respect to the clicked point. Extend: Extends a line or an arc to a boundary line, arc, ellipse, arc of ellipse or a point in space. Split: Splits a line or an arc into two, converts a circle into an arc while keeping most of the constraints. introduced in version 0.20 External Geometry: Creates an edge linked to external geometry. CarbonCopy: Copies the geometry of another sketch. Construction Mode: Toggles sketch geometry from/to construction mode. Construction geometry is shown in blue and is discarded outside of Sketch editing mode.

Sketcher constraints

Constraints are used to define lengths, set rules between sketch elements, and to lock the sketch along the vertical and horizontal axes. Some constraints require use of Helper constraints.

Geometric constraints

These constraints are not associated with numeric data. Coincident: Affixes a point onto (coincident with) one or more other points. Point On Object: Affixes a point onto another object such as a line, arc, or axis. Vertical: Constrains the selected lines or polyline elements to a true vertical orientation. More than one object can be selected before applying this constraint. Horizontal: Constrains the selected lines or polyline elements to a true horizontal orientation. More than one object can be selected before applying this constraint. Parallel: Constrains two or more lines parallel to one another. Perpendicular: Constrains two lines perpendicular to one another, or constrains a line perpendicular to an arc endpoint. Tangent: Creates a tangent constraint between two selected entities, or a co-linear constraint between two line segments. A line segment does not have to lie directly on an arc or circle to be constrained tangent to that arc or circle. Equal: Constrains two selected entities equal to one another. If used on circles or arcs their radii will be set equal. Symmetric: Constrains two points symmetrically about a line, or constrains the first two selected points symmetrically about a third selected point. Block: it blocks an edge from moving, that is, it prevents its vertices from changing their current positions. It should be particularly useful to fix the position of B-Splines. See the Block Constraint forum topic.

Dimensional constraints

These are constraints associated with numeric data, for which you can use the expressions. The data may be taken from a spreadsheet. Lock: Constrains the selected item by setting vertical and horizontal distances relative to the origin, thereby locking the location of that item. These constraint distances can be edited later. Horizontal distance: Fixes the horizontal distance between two points or line endpoints. If only one item is selected, the distance is set to the origin. Vertical distance: Fixes the vertical distance between 2 points or line endpoints. If only one item is selected, the distance is set to the origin. Distance: Defines the distance of a selected line by constraining its length, or defines the distance between two points by constraining the distance between them. Radius: Defines the radius of a selected arc or circle by constraining the radius. Diameter: Defines the diameter of a selected arc or circle by constraining the diameter. Radiam: Automatically defines radius/diameter of a selected arc or circle (weight for a B-spline pole, diameter for a complete circle, radius for an arc) introduced in version 0.20 Angle: Defines the internal angle between two selected lines.

Special constraints

Snell's Law: Constrains two lines to obey a refraction law to simulate the light going through an interface. Internal alignment: Aligns selected elements to selected shape (e.g. a line to become major axis of an ellipse).

Constraint tools

The following tools can be used the change the effect of constraints: Toggle driving/reference constraint: Toggles the toolbar or the selected constraints to/from reference mode. Activate/Deactivate constraint: Enable or disable an already placed constraint. introduced in version 0.19

Sketcher tools

Select solver DOFs: Highlights in green the geometry with degrees of freedom (DOFs), i.e. not fully constrained. Close Shape: Creates a closed shape by applying coincident constraints to endpoints. Connect Edges: Connect sketcher elements by applying coincident constraints to endpoints. Select Constraints: Selects the constraints of a sketcher element. Select Elements Associated with constraints: Select sketcher elements associated with constraints. Select Redundant Constraints: Selects redundant constraints of a sketch. Select Conflicting Constraints: Selects conflicting constraints of a sketch. Show/Hide internal geometry: Recreates missing/deletes unneeded internal geometry of a selected ellipse, arc of ellipse/hyperbola/parabola or B-spline. Select Origin: Selects the origin of a sketch. Select Vertical Axis: Selects the vertical axis of a sketch. Select Horizontal Axis: Selects the horizontal axis of a sketch. Symmetry: Copies a sketcher element symmetrical to a chosen line. Clone: Clones a sketcher element. Copy: Copies a sketcher element. Move: Moves the selected geometry taking as reference the last selected point. Rectangular Array: Creates an array of selected sketcher elements. Remove Axes Alignment: Remove axes alignment while trying to preserve the constraint relationship of the selection. introduced in version 0.20 Delete All Geometry: Deletes all geometry from the sketch. Delete All Constraints: Deletes all constraints from the sketch.

Sketcher B-spline tools

Show/hide B-spline degree Show/hide B-spline control polygon Show/hide B-spline curvature comb Show/hide B-spline knot multiplicity Show/hide B-spline control point weight, introduced in version 0.19 Convert geometry to B-spline Increase B-spline degree Decrease B-spline degree, introduced in version 0.19 Increase knot multiplicity Decrease knot multiplicity

Sketcher virtual space

Switch Virtual Space: Allows you to hide all constraints of a sketch and make them visible again.

Preferences

Preferences: Preferences for the Sketcher workbench.

Best Practices

Every CAD user develops his own way of working over time, but there are some useful general principles to follow. A series of simple sketches is easier to manage than a single complex one. For example, a first sketch can be created for the base 3D feature (either a pad or a revolve), while a second one can contain holes or cutouts (pockets). Some details can be left out, to be realized later on as 3D features. You can choose to avoid fillets in your sketch if there are too many, and add them as a 3D feature. Always create a closed profile, or your sketch won't produce a solid, but rather a set of open faces. If you don't want some of the objects to be included in the solid creation, turn them to construction elements with the Construction Mode tool. Use the auto constraints feature to limit the number of constraints you'll have to add manually. As a general rule, apply geometric constraints first, then dimensional constraints, and lock your sketch last. But remember: rules are made to be broken. If you're having trouble manipulating your sketch, it may be useful to constrain a few objects first before completing your profile. If possible, center your sketch to the origin (0,0) with the lock constraint. If your sketch is not symmetric, locate one of its points to the origin, or choose nice round numbers for the lock distances. In v0.12, external constraints (constraining the sketch to existing 3D geometry like edges or to other sketches) are not implemented. This means that to locate following sketches geometry to your first sketch, you'll need to set distances relative to your first sketch manually. A lock constraint of (25,75) from the origin is more easily remembered than (23.47,73.02). If you have the possibility to choose between the Length constraint and the Horizontal or Vertical Distance constraints, prefer the latter. Horizontal and Vertical Distance constraints are computationally cheaper. In general, the best constraints to use are: Horizontal and Vertical Constraints; Horizontal and Vertical Length Constraints; Point-to-Point Tangency. If possible, limit the use of these: the general Length Constraint; Edge-to-Edge Tangency; Fix Point Onto a Line Constraint; Symmetry Constraint. If in doubt about the validity of a sketch once it is complete (features turn green), close the Sketcher dialog, switch to the Check geometry.

Tutorials

Sketcher tutorial by chrisb. This is a 70-page long PDF document that serves as a detailed manual for the sketcher. It explains the basics of Sketcher usage, and goes into a lot of detail about the creation of geometrical shapes, and each of the constraints. Basic Sketcher Tutorial for beginners Sketcher Micro Tutorial - Constraint Practices Sketcher requirement for a sketch Minimum requirement for a sketch and Complete determination of a sketch

Scripting

The Sketcher scripting page contains examples on how to create constraints from Python scripts.


Manual:Preparing models for 3D printing

One of the main uses of FreeCAD is to produce real-world objects. These can be designed in FreeCAD, and then made real in different ways, such as communicated to other people who will then build them, or, more and more frequently, sent directly to a 3D printer or a CNC mill. This chapter will show you how to get your models ready to send to these machines. If you have been cautious while modeling, most of the difficulty you might encounter when printing your model in 3D has already been avoided. This involves basically: Making sure that your 3D objects are solid. Real-world objects are solid, the 3D model must be solid too. We saw in earlier chapters that FreeCAD helps you a lot in that regard, and that the PartDesign Workbench will notify you if you do an operation that prevents your model to stay solid. The Check Geometry tool that is handy to check further for possible defects. Making sure about the dimensions of your objects. One millimeter will be one millimeter in real-life. Every dimension matters. Controlling the degradation. No 3D printing or CNC milling system can take FreeCAD files directly. Most of them will only understand a machine language called G-Code. G-code has dozens of different dialects, each machine or vendor usually has its own. The conversion of your models into G-Code can be easy and automatic, but you can also do it manually, with total control over the output. In any case, some loss of quality of your model will unavoidably occur during the process. When printing in 3D, you must always make sure this loss of quality stays below your minimum requirements. Below, we will assume that the first two criteria are met, and that by now you are able to produce solid objects with correct dimensions. We will now see how to address the third point. 1 Exporting to slicers 2 Converting objects to meshes 3 Using Slic3r 4 Using the Cura addon 5 Generating G-code 6 Videos

Exporting to slicers

This is the technique most commonly used for 3D printing. The 3D object is exported to another program (the slicer) which will generate the G-code from the object, by slicing it into thin layers (hence the name), which will reproduce the movements that the 3D printer will do. Since many of those printers are home-built, there are often small differences from one to the other. These programs usually offer advanced configuration possibilities that allow you to tailor the output exactly for the features of your 3D printer. Actual 3D printing, however, is too vast a subject for this manual. But we will see how to export and use these slicers to check that the output is correct.

Converting objects to meshes

None of the slicers will, at this time, directly take the solid geometry as we produce in FreeCAD. So we will need to convert any object we want to 3D print into a mesh first, that the slicer can open. Fortunately, as much as converting a mesh to a solid is a complicated operation, the contrary, converting a solid to a mesh, is very straightforward. All we need to be careful about, is that it is here that the degradation we mentioned above will occur. We need to check that the degradation stays within acceptable limits. All the mesh handling, in FreeCAD, is done by another specific workbench, the Mesh Workbench. This workbench contains, in addition to the most important tools that convert between Part and Mesh objects, several utilities meant to analyze and repair meshes. Although working with meshes is not the focus of FreeCAD, when working with 3D modeling, you often need to deal with mesh objects, since their use is very widespread among other applications. This workbench allows you to handle them fully in FreeCAD. Let's convert one of the objects we modelled in the previous chapters, such as the lego piece (which can be downloaded from the end of the previous chapter). Open the FreeCAD file containing the lego piece. Switch to the Mesh Workbench Select the lego brick Select menu Meshes → Create Mesh from Shape A task panel will open with several options. Some additional meshing algorithms (Mefisto or Netgen) might not be available, depending on how your version of FreeCAD was compiled. The Standard meshing algorithm will always be present. It offers less possibilities than the two others, but is totally sufficient for small objects that fit into the maximum print size of a 3D printer. Select the Standard mesher, and leave the deviation value to the default value of 0.10. Press Ok. A mesh object will be created, exactly on top of our solid object. Either hide the solid, or move one of the objects aside, so you can compare both. Change the View → Display Mode property of the new mesh object to Flat Lines, in order to see how the triangulation occurred. If you are not happy, and think that the result is too coarse, you can repeat the operation, lowering the deviation value. In the example below, the left mesh used the default value of 0.10, while the right one uses 0.01: In most cases, though, the default values will give a satisfying result. We can now export our mesh to a mesh format, such as STL, which is currently the most widely used format in 3D printing, by using menu File → Export and choosing the STL file format. If you don't own a 3D printer, it is usually very easy to find commercial services that will print and send you the printed objects by mail. Among the famous ones are Shapeways and Sculpteo, but you will usually find many others in your own city. In all major cities, you will nowadays find Fab labs, which are workshops equipped with a range of 3D manufacturing machines, almost always including at least one 3D printer. Fab labs are usually community spaces, that will let you use their machines, for a fee or for free depending on the Fab lab, but also teach you how to use them, and promote other activities around 3D manufacturing.

Using Slic3r

Slic3r is an application that converts STL objects into G-code that can be sent directly to 3D printers. Like FreeCAD, it is free, open source and runs on Windows, Mac OS and Linux. Correctly configuring things for 3D printing is a complicated process, where you must have a good knowledge of your 3D printer, so it is not very useful to generate G-code before actually going to print (your G-code file might not work well on another printer), but it is useful for us anyway, to check that our STL file will be printable without problems. This is our exported STL file opened in Slic3r. By using the preview tab, and moving the right slider, we can visualize the path that the 3D printer head will follow to construct our object.

Using the Cura addon

Cura is another free and open source slicer application for Windows, Mac and Linux, maintained by the 3D printer maker Ultimaker. Some FreeCAD users have created a Cura Workbench that uses cura internally. The Cura Workbench is available from the FreeCAD addons repository. To use the Cura Workbench, you also need to install Cura itself, which is not included in the workbench. Once you have installed both Cura and the Cura Workbench, you will be able to use it to produce the G-code file directly from Part objects, without the need to convert them to meshes, and without the need to open an external application. Producing another G-code file from our Lego brick, using the Cura Workbench this time, is done as follows: Load the file containing our Lego brick (it can be downloaded at the end of the previous chapter) Switch to the Cura Workbench Setup the printer space by choosing menu 3D printing → Create a 3D printer definition. Since we aren't going to print for real, we can leave the settings as they are. The geometry of the printing bed and available space will be shown in the 3D view. Move the Lego brick to a suitable location, such as the center of the printing bed. Remember that PartDesign objects cannot be moved directly, so you need either to move its very first sketch (the first rectangle), or to move (and print) a copy, which can be made with the Part -> Create Simple Copy tool. The copy can be moved, for example with Draft → Move. Select the object to be printed, and select menu 3D printing → Slice with Cura Engine. In the task panel that will open, make sure the path to the Cura executable is correctly set. Since we are not going to really print, we can leave all other options as they are. Press Ok. Two files will be generated in the same directory as your FreeCAD file, an STL file and a G-code file. The generated G-code can also be re-imported into FreeCAD (using the slic3r preprocessor) for checking.

Generating G-code

FreeCAD also offers more advanced ways to generate G-code directly. This is often much more complicated than using automatic tools as we saw above, but has the advantage to let you fully control the output. This is usually not needed when using 3D printers, but becomes very important when dealing with CNC milling, as the machines are much more complex. G-code path generation in FreeCAD is done with the Path Workbench. It features tools that generate full machine paths and others that generate only parts of a G-code project, that can then be assembled to form a whole milling operation. Generating CNC milling paths is another subject that is much too vast to fit in this manual, so we are going to show how to build a simple Path project, without caring much about most of the details of real CNC machining. Load the file containing our lego piece, and switch to the Path Workbench. Since the final piece doesn't contain anymore a rectangular top face, hide the final lego piece, and show the first cubic pad that we did, which has a rectangular top face. Select the top face and press the Profile button. Set its Offset property to 1mm. Then, let's duplicate this first loop a couple of times, so the tool will carve out the whole block. Select the Profile path, and press the Array button. Set the Copies property of the array to 8, and its Offset to -2mm in the Z direction, and move the placement of the array by 2mm in the Z direction, so the cutting will start a bit above the pad, and include the height of the dots too. Now we have defined a path that, when followed by the milling machine, will carve a rectangular volume out of a block of material. We now need to carve out the space between the dots, in order to reveal them. Hide the Pad, and show the final piece again, so we can select the face that lies between the dots. Select the top face, and press the Pocket Shape button. Set the Offset property to 1mm, and the retraction height to 20mm. That is the height to where the cutter will travel when switching from one loop to another. Otherwise, the cutter might cut right through one of our dots: Once again, make an array. Select the Pocket object, and press the Array button. Set the Copies number to 1 and the offset to -2mm in the Z direction. Move the placement of the array by 2mm in the Z direction. Our two operations are now done: Now all that is left to do is to join these two operations into one. This can be done with a Path Job. Press the Job button. Set the Use Placements property of the project is to True, because we changed the placement of the arrays, and we want that to be taken into account in the project. In the tree view, drag and drop the two arrays into the project. You can reorder the arrays inside the project if needed, by double-clicking it. The project can now be exported to G-code, by selecting it, choosing menu File -> Export, selecting the G-code format, and in the pop-up dialog that will open, selecting a post-processing script according to your machine. There are many applications available to simulate the real cutting, one of them that is also multi-platform and open source, like FreeCAD, is Camotics. Downloads The STL file generated in this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/lego.stl The file generated during this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/path.FCStd The G-code file generated in this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/lego.gcode Read more The Mesh Workbench The STL file format Slic3r Cura The Cura Workbench The Path Workbench Camotics

Videos

How To Use FreeCAD For 3D Printing | Using The Realthunder Branch A video playlist by Maker Tales about how to use FreeCAD for 3D printing.


Manual:Creating renderings

In computer speak, the word rendering is used to describe a nice image produced from a 3D model. Of course, we could say that what we see in the FreeCAD 3D view is already nice. However, anybody who has seen a recent Hollywood movie, knows that it is possible to produce images with a computer that are almost indistinguishable from a photograph. Of course, producing photo-realistic images requires a lot of work, in addition to a 3D application that offers specific tools for that purpose, such as precise controls for materials and lighting. Because FreeCAD is an application geared more towards technical modelling, it does not feature any advanced rendering tools. +Fortunately, the open source world offers many applications to produce realistic images. The most famous one is probably Blender, which is very popular, and widely used in the film and gaming industries. 3D models can very easily and faithfully be exported from FreeCAD and imported into Blender, where you can add realistic materials and illumination, and produce the final images or even animations. Some other open source rendering tools are made to be used inside other applications, and will take care of doing the complex calculations to produce realistic images. Through its Raytracing Workbench, FreeCAD can use two of these rendering tools: POV-Ray and Luxrender. POV-Ray is a very old project, and is considered a classical raytracing engine, while Luxrender is much newer, and is categorized as an unbiased renderer. Both have their strengths and weaknesses, depending on the type of image one wants to render. The best way to know is to look at examples on each engine's website.

Installation

Before being able to use the Raytracing Workbench in FreeCAD, one of these two rendering applications needs to be installed on your system. This is usually very straightforward. They both provide installers for many platforms or are usually included in the software repositories of most Linux distributions. Once POV-Ray or Luxrender is installed, we need to set the path to their main executable in the FreeCAD preferences. This is usually only required on Windows and Mac. On Linux, FreeCAD will pick it from the standard locations. The location of the povray or luxrender executables can be found by searching your system for files named povray (or povray.exe on Windows) and luxrender (or luxrender.exe on Windows). In this preferences screen we can also set the desired image size we want to produce.

Rendering with PovRay

We will use the table we have been modelling in the traditional modeling chapter to produce renderings with PovRay and Luxrender. Start by loading the table.FCStd file that we modelled earlier or from the link at the bottom of this chapter. Press the small down arrow next to the New Povray project button, and choose the RadiosityNormal template A warning message might appear telling you that the current 3D view is not in perspective mode and the rendering will therefore differ. Correct this by choosing No, choosing menu View->Perspective view and choosing the RadiosityNormal template again. You can also try other templates after you create a new project, simply by editing its Template property. A new project has now been created: The new project has adopted the point of view of the 3D view as it was at the moment we pressed the button. We can change the view, and update the view position stored in the Povray project anytime, by pressing the Reset camera button. The Raytracing Workbench works the same way as the Drawing Workbench: Once a project folder is created, we must add Views of our objects to it. We can now do that by selecting all the objects that compose the table, and press the Insert part button: The views have taken the color and transparency values from their original parts, but you can change that in the properties of each individual view if you wish. We are now ready to produce our first Povray render. Press the Render button. Note for windows users: when receiving (in Povray) a warning saying "I/O restrictions prohibit write access ..." open Povray choose "Options > Script I/O Restrictions" and make sure it is set to "No Restrictions" retry render You will be asked to give a file name and path for the .png image that will be saved by Povray. Povray will then open and calculate the image. When this is done, click the image to close the Povray window. The resulting image will be loaded in FreeCAD:

Rendering with LuxRender

Rendering with Luxrender works almost the same way. We can leave our file open and create a new Luxrender project in the same file, or reload it to start from scratch. Press the little down arrow next to the New Luxrender project button and choose the LuxOutdoor template. Select all the components of the table. If you still have the Povray project in your document, be sure to also select the Luxrender project itself, so the views created in the next step won't go in the wrong project by mistake. Press the Insert part button. Select the Luxrender project, and press the Render button. Luxrender works differently to Povray. When you start the render, the Luxrender application will open and immediately start rendering: If you leave that window open, Luxrender will continue calculating and rendering forever, progressively refining the image. It is up to you to decide when the image has reached a sufficient quality for your needs, and stop the render. There are also many controls to play with, on the left panel. All these controls will change the aspect of the image being rendered on the fly, without stopping the rendering. When you feel the quality is good enough, press Render->stop, and then File->Export to image->Tonemapped low dynamic range to save the rendered image to a png file. You can greatly extend the rendering possibilities of FreeCAD by creating new templates for Povray or Luxrender. This is explained in the Raytracing Workbench documentation. Downloads The table model: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/table.FCStd The file produced during this exercise: https://github.com/yorikvanhavre/FreeCAD-manual/blob/master/files/render.FCStd Read more The Raytracing Workbench Blender POV-Ray Luxrender


Robot Workbench

Introduction

Robot workbench icon The Robot Workbench is a tool to simulate a standard 6-axis industrial robot, like Kuka. You can do the following tasks: Set up a simulation environment with a robot and work pieces. Create and fill up movement trajectories. Decompose features of a CAD part to a trajectory. Simulate the robot movement and reaching distance. Export the trajectory to a robot program file. To get started try the Robot tutorial, and see the programming interface in the RobotExample.py example file. 1 Introduction 2 Tools 2.1 Robots 2.2 Trajectories 2.2.1 Non parametric trajectories 2.2.2 Parametric trajectories 3 Scripting 4 Tutorials

Tools

Here the principal commands you can use to create a robot set-up.

Robots

The tools to create and manage the 6-Axis robots Create a robot: Insert a new robot into the scene Simulate a trajectory: Opens the simulation dialog and lets you simulate Export a trajectory: Export a robot program file Set home position: Set the home position of a robot Restore home position: move the robot to its home position

Trajectories

Tools to create and manipulate trajectories. There are two kinds, the parametric and non parametric ones.

Non parametric trajectories

Create a trajectory: Inserts a new empty trajectory-object into the scene Set the default orientation: Set the orientation way-points gets created by default Set the default speed parameter: Set the default values for way-point creation Insert a waypoint: Insert a way-point from the current robot position into a trajectory Insert a waypoint preselected: Insert a way-point from the current mouse position into a trajectory

Parametric trajectories

Create a trajectory out of edges: Insert a new object which decompose edges to a trajectory Dress-up a trajectory: Lets you override one or more properties of a trajectory Trajectory compound: Create a compound out of some single trajectories

Scripting

See the Robot API example for a description of the functions used to model the robot displacements.

Tutorials

Robot 6-Axis VRML Preparation for Robot Simulation


Python scripting tutorial

Introduction

Python is a programming language that it relatively easy to learn and understand. It is open-source and multi-platform, and can be used for many purposes: from simple shell scripts to very complex programs. But its most widespread use is as a scripting language embedded in other applications. That is how it is used inside FreeCAD. From the Python console, or from custom scripts, you can control FreeCAD and make it perform very complex operations. For example, from a Python script, you can: Create new objects. Modify existing objects. Modify the 3D representation of those objects. Modify the FreeCAD interface. There are several ways to use Python in FreeCAD: From the FreeCAD Python interpreter, where you can issue commands in a "command line"-style interface. From macros, which are a convenient way to quickly add a missing tool to the FreeCAD interface. From external scripts, which can used to create quite complex solutions, even entire Workbenches. In this tutorial, we'll work on a couple of basic examples to get you started, but there is much more documentation about Python scripting available on this wiki. If you are totally new to Python and want to understand how it works, we also have a basic introduction to Python. Before proceeding with Python scripting, go to Edit → Preferences → General → Output window and check two boxes: Redirect internal Python output to report view. Redirect internal Python errors to report view. Then go to View → Panels and check: Report view.

Writing Python code

There are two ways to write Python code in FreeCAD. In the Python console (select View → Panels → Python console from the menu) or in the Macro editor (select Macro → Macros... from the menu). In the console you write Python commands one by one, executing them by pressing Enter, while macros can contain more complex code made up of several lines, executed only when the macro is executed. The FreeCAD Python console In this tutorial you can use both methods. You can copy-paste each line in the Python console and then press Enter, or copy-paste the entire code in a new Macro window.

Exploring FreeCAD

Let's start by creating a new empty document: doc = FreeCAD.newDocument() If you type this in the FreeCAD Python console, you will notice that as soon as you type FreeCAD. a window pops up, allowing to quickly autocomplete the rest of your line. Even better, each entry in the autocomplete list has a tooltip explaining what it does. This makes it easier to explore the available functionality. Before choosing newDocument, have a look at the other options. The autocomplete mechanism of the FreeCAD Python console Now our new document will be created. This is similar to pressing the Std New button on the toolbar. In fact most buttons in FreeCAD do nothing more than execute one or more lines of Python code. Even better, you can set an option in Edit → Preferences → General → Macro to Show script commands in python console. This will print in the console all Python code executed when you press buttons. Very useful for learning how to reproduce actions in Python. Now let's get back to our document and see what we can do with it: doc. Explore the available options. Usually names that begin with a capital letter are attributes, they contain a value, while names that begin with a lower case letter are functions (also called methods), they "do something". Names that begin with an underscore are usually there for the internal working of the module, and you shouldn't care about them. Let's use one of the methods to add a new object to our document: box = doc.addObject("Part::Box", "myBox") Nothing happens. Why? Because FreeCAD is made for the big picture. One day, it will work with hundreds of complex objects, all depending each other. Making a small change somewhere could have a big impact; you may need to recalculate the whole document which could take a long time. For that reason almost no command updates the scene automatically. You must do it manually: doc.recompute() Now our box appeared. Many of the buttons that add objects in FreeCAD actually do two things: add the object, and recompute. If you turned on the Show script commands in python console option above, try adding a sphere with the GUI button; you'll see the two lines of Python code being executed one after the other. Now let's explore the contents of our box: box. You'll immediately see a couple of very interesting things such as: box.Height This will print the current height of our box. Now let's try to change that: box.Height = 5 If you select your box with the mouse, you'll see that in the Property editor, on the Data tab, our DataHeight property appears. All properties of a FreeCAD object that appear there (and also on the View tab, more about that later), are directly accessible in Python too, by their names, like we did with the DataHeight property. Try changing the other dimensions of the box.

Vectors and placements

Vectors are a very fundamental concept in any 3D application. A vector is a list of 3 numbers (x, y and z), describing a point or position in 3D space. Many things can be done with vectors, such as additions, subtractions, projections and much more. In FreeCAD vectors work like this: myvec = FreeCAD.Vector(2, 0, 0) myvec.x myvec.y othervec = FreeCAD.Vector(0, 3, 0) sumvec = myvec.add(othervec) Another common feature of FreeCAD objects is their placement. Each object has a DataPlacement property, which contains the DataBase (position) and DataRotation (orientation) of the object. It is easy to manipulate, for example to move our object: box.Placement box.Placement.Base box.Placement.Base = sumvec otherpla = FreeCAD.Placement() box.Placement = otherpla Now you must understand a couple of important concepts before we get further.

App and Gui

FreeCAD has been designed so that it can also be used without its user interface, as a command-line application. Almost every object in FreeCAD therefore consists of two parts: an Object, its "geometry" component, and a ViewObject, its "visual" component. When you work in command-line mode, the geometry part is present, but the visual part is disabled. To illustrate the concept let's look at our cube object. The geometric properties of the cube, such as its dimensions, position, etc. are stored in the Object. While its visual properties, such as its color, line thickness, etc. are stored in the ViewObject. This corresponds to the Data and View tabs in the Property editor. The view object of an object is accessed like this: vo = box.ViewObject Now you can also change the properties on the View tab: vo.Transparency = 80 vo.hide() vo.show() When you start FreeCAD, the Python console already loads two base modules: FreeCAD and FreeCADGui (which can also be accessed by their shortcuts App and Gui). They contain all kinds of generic functionality to work with documents and their objects. To illustrate our concept, see that both FreeCAD and FreeCADGui contain an ActiveDocument attribute, which is the currently opened document. FreeCAD.ActiveDocument and FreeCADGui.ActiveDocument are not the same object however. They are the two components of a FreeCAD document, and they contain different attributes and methods. For example, FreeCADGui.ActiveDocument contains ActiveView, which is the currently opened 3D view.

Modules

The true power of FreeCAD lies in its faithful modules, with their respective workbenches. The FreeCAD base application is more or less an empty container. Without its modules it can do little more than create new, empty documents. Each module not only adds new workbenches to the interface, but also new Python commands and new object types. As a result several different, and even totally incompatible, object types can coexist in the same document. The most important modules in FreeCAD that we'll look at in this tutorial are: Part, Mesh, Sketcher and Draft. Sketcher and Draft both use the Part module to create and handle their geometry. While Mesh is totally independent, and handles its own objects. More about that below. You can check all the available base object types for the current document like this: doc.supportedTypes() The different FreeCAD modules are not automatically loaded in the Python console. This is to avoid having a very slow startup. Modules are loaded only when you need them. So, for example, to explore what's inside the Part module: import Part Part. But we'll talk more about the Part module below.

Mesh module

Meshes are a very simple kind of 3D object, used for example by Sketchup, Blender and 3D Studio Max. They are composed of 3 elements: points (also called vertices), lines (also called edges) and faces. In many applications, FreeCAD included, faces can have only 3 vertices. Of course, nothing prevents you from having a bigger face made up of several coplanar triangles. Meshes are simple, but because they are simple you can easily have millions of them in a single document. However, in FreeCAD they have less use and are mostly there so you can import objects in mesh formats (.stl, .obj) from other applications. The Mesh module was also used extensively as the main test module in the first month of FreeCAD's life. Mesh objects and FreeCAD objects are different things. You can see the FreeCAD object as a container for a Mesh object (and as we'll see below, for Part objects also). So in order to add a mesh object to FreeCAD, we must first create a FreeCAD object and a Mesh object, then add the Mesh object to the FreeCAD object: import Mesh mymesh = Mesh.createSphere() mymesh.Facets mymesh.Points meshobj = doc.addObject("Mesh::Feature", "MyMesh") meshobj.Mesh = mymesh doc.recompute() This is a standard example that uses the createSphere() method to create a sphere, but you can also create custom meshes from scratch by defining their vertices and faces. Read more about mesh scripting...

Part module

The Part module is the most powerful module in the whole of FreeCAD. It allows you to create and manipulate BRep objects. BREP stands for "Boundary Representation". A BREP object is defined by surfaces that enclose and define an inner volume. Unlike meshes, BREP objects can have a wide variety of components from planar faces to very complex NURBS surfaces. The Part module is based on the powerful OpenCasCade library, which allows a wide range of complex operations to be performed on those objects, such as boolean operations, filleting, lofts, etc. The Part module works the same way as the Mesh module: You create a FreeCAD object, a Part object, then add the Part object to the FreeCAD object: import Part myshape = Part.makeSphere(10) myshape.Volume myshape.Area shapeobj = doc.addObject("Part::Feature", "MyShape") shapeobj.Shape = myshape doc.recompute() The Part module (like the Mesh module) also has a shortcut that automatically creates a FreeCAD object and adds a shape to it, so you can shorten the last three lines to: Part.show(myshape) By exploring the contents of myshape, you will notice many interesting subcomponents such as Faces, Edges, Vertexes, Solids and Shells, and a wide range of geometry operations such as cut (subtraction), common (intersection) or fuse (union). The Topological data scripting page explains all that in detail. Read more about part scripting...

Draft module

FreeCAD features many more modules, such as Sketcher and Draft, that also create Part objects. These modules add additional parameters to the objects created, or even implement a whole new way to handle the Part geometry in them. Our box example above is a perfect example of a parametric object. All you need to define the box is to specify the parameters height, width and length. Based on those, the object will automatically calculate its Part shape. FreeCAD allows you to create such objects in Python. The Draft module adds 2D parametric object types (which are all Part objects) such as lines and circles, and also provides some generic functions that not only work on Draft objects, but on any Part object. To explore what is available, simply do: import Draft rec = Draft.makeRectangle(5, 2) mvec = FreeCAD.Vector(4, 4, 0) Draft.move(rec, mvec) Draft.move(box, mvec)

Interface

The FreeCAD user interface is made with Qt, a powerful graphical interface system, responsible for drawing and handling all the controls, menus, toolbars and buttons around the 3D view. Qt provides a module, PySide, which allows Python to access and modify Qt interfaces such as FreeCAD's. Let's try to fiddle with the Qt interface and produce a simple dialog: from PySide import QtGui QtGui.QMessageBox.information(None, "Apollo program", "Houston, we have a problem") Notice that the dialog that appears has the FreeCAD icon in its toolbar, meaning that Qt knows that the order has been issued from inside the FreeCAD application. It is possible to manipulate any part of the FreeCAD interface. Qt is a very powerful interface system that allows you to do very complex things. It also has some easy-to-use tools such as the Qt Designer with which you can design dialogs graphically and then add them to the FreeCAD interface with a few lines of Python code. Read more about PySide here...

Macros

Now that you have a good understanding of the basics, where are we going to keep our Python scripts, and how are we going to launch them inside FreeCAD? There is an easy mechanism for that, called Macros. A macro is a Python script that can be added to a toolbar and launched via a mouse click. FreeCAD provides you with a simple text editor (Macro → Macros... → Create) where you can write or paste scripts. Once the script is done, use Tools → Customize... → Macros to define a button for it that can be added to toolbars. Now you are ready for more in-depth FreeCAD scripting. So head on to the Power users hub!


Scripts

Introduction

With Scripting we mean create topological objects using FreeCAD's Python interpreter. FreeCAD could be used a "very good" replacement of OpenSCAD, manìinly beacause it has a real Python interpreter, that means that it has a real programming language on board, almost everything you could do with the GUI, is doable with a Python Script. Sadly information about scripting in the documentation, and even in this wiki are scattered around and lacks of "writing" uniformity and most of them are explained in a too technical manner.

Wetting you appetite

The first obstacle in an easy way to scripting is that there is no direct way to access the FreeCAD internal Python editor through a menu item or a icon on the toolbar area, but knowing that FreeCAD opens a file with a .py extension in the internal Python editor, the most simple trick is create in your favorite text editor and then open it with the usual command File → Open. To make the things in a polite way, the file has to be written with some order, FreeCAD Python editor have a good "Syntax HIghlighting" that lacks in many simple editors like Windows Notepad or some basic Linux editors, so it is sufficient to write these few lines: """script.py Primo script per FreeCAD """
Save them with a meaningfull name with .py extension and load the resulting file in FreeCAD, with the said File - Open command.
A minimal example of what is necessary to have in a script is shown in this portion of code that you could be use as a template for almost any future script: """filename.py Here a short but significant description of what the script do """ import FreeCAD from FreeCAD import Base, Vector import Part from math import pi, sin, cos DOC = FreeCAD.activeDocument() DOC_NAME = "Pippo" def clear_doc(): """ Clear the active document deleting all the objects """ for obj in DOC.Objects: DOC.removeObject(obj.Name) def setview(): """Rearrange View""" FreeCAD.Gui.SendMsgToActiveView("ViewFit") FreeCAD.Gui.activeDocument().activeView().viewAxometric() if DOC is None: FreeCAD.newDocument(DOC_NAME) FreeCAD.setActiveDocument(DOC_NAME) DOC = FreeCAD.activeDocument() else: clear_doc() # EPS= tolerance to use to cut the parts EPS = 0.10 EPS_C = EPS * -0.5 Some tricks are incorporated in the above code:
import FreeCAD This line import FreeCAD in the FreeCAD Python interpreter, it may seem a redundant thing, but it isn't. from FreeCAD import Base, Vector Base and Vector are widely used in FreeCAD scripting, import them in this manner will save you to invoke them with FreeCAD.Vector or FreeCAD.Base instead of Base or Vector, this will save many keystrokes and make codelines much smaller.
Let's start with a small script that does a very small job, but display the power of this approach. def cubo(nome, lung, larg, alt): obj_b = DOC.addObject("Part::Box", nome) obj_b.Length = lung obj_b.Width = larg obj_b.Height = alt DOC.recompute() return obj_b # objects definition obj = cubo("test_cube", 5, 5, 5) setview() Put these lines after the "template" code and press the green arrow in the Macro toolbar You will see some magic things, a new document is open named "Pippo" (Italian name of Goofy) and you will see in the 3d view a Cube, like the one in the image below. Test Cube

Something more...

Not too amazing? Yes, but we have to start somewhere, we can do the same thing with a Cylinder, add these lines of code after the cubo( method and before the line # objects definition. def base_cyl(nome, ang, rad, alt ): obj = DOC.addObject("Part::Cylinder", nome) obj.Angle = ang obj.Radius = rad obj.Height = alt DOC.recompute() return obj Even here nothing too exciting. But please note some peculiarities: The absence of the usual reference to the App., present in many Documentation code snippets, is deliberate, this code could be used even invoking FreeCAD as a module in an external Python interpreter, the thing is not easily doable with an AppImage, but with some care it could be done. Plus in the standard Python motto that "better explicit than implicit" App. is explaining in a very "poor" way where the things are from. Note the use of the "constant" name assigned to the active Document in DOC = FreeCAD.activeDocument(); activeDocument is not a "constant" in a strict sense, but in a "semantical" way is our "active Document", that for our use is a proper "constant" so the Python convention to use the "ALL CAPS" name for "constants", not to mention that DOC is much shorten than FreeCAD.activeDocument(). Every method returns a geometry, this will be clear in the continuation of the page. Geometry didn't have the Placement property, when using the simple geometries to make more complex geometry, managing Placement is a awkward thing. Now what to do with this geometries? Let's introduce boolean operations. As a starter example put these lines after base_cyl(..., this create a method for a Fusion also know as Union operation: def fuse_obj(nome, obj_0, obj_1): obj = DOC.addObject("Part::Fuse", nome) obj.Base = obj_0 obj.Tool = obj_1 obj.Refine = True DOC.recompute() return obj Nothing exceptional also here, note however the uniformity in method coding; This approach is more linear that those seen around other tutorial on scripting, this "linearity" help greatly in readability and also with cut-copy-paste operations. Let's use the geometries, delete lines below the code section starting with # objects definition, and insert the following lines: # objects definition obj = cubo("cubo_di_prova", 5, 5, 5) obj1 = base_cyl('primo cilindro', 360,2,10) fuse_obj("Fusione", obj, obj1) setview() Launch the script with the green arrow and we will see in the 3D view something like: cube and cylinder

Placement

Placement Concept is relatively complex, see Aeroplane Tutorial for a more deep explanation. We usually are in need of placing geometries respect each other, when building complex object this is a recurring task, the most common way is to use the geometry Placement property. FreeCAD offer a wide choice of ways to set this property, one is more tailored to another depending the knowledge and the background of the user, but the more plain writing is explained in the cited Tutorial, it use a peculiar definition of the Rotation portion of Placement, quite easy to learn. FreeCAD.Placement(Vector(0,0,0), FreeCAD.Rotation(10,20,30), Vector(0,0,0)) But over other consideration, one thing is crucial, geometry reference point, in other word the point from which the object is modeled by FreeCAD, as described in this table, copied from Placement:
Object Reference Point
Part.Box left (minx), front (miny), bottom (minz) vertex
Part.Sphere center of the sphere (ie centre of bounding box)
Part.Cylinder center of the bottom face
Part.Cone center of bottom face (or apex if bottom radius is 0)
Part.Torus center of the torus
Features derived from Sketches the Feature inherits the Position of the underlying Sketch. Sketches always start with Position = (0,0,0). This position corresponds to the origin in the sketch.

This information has to be kept in mind especially when we have to apply a rotation. Some examples may help, delete all the line after base_cyl method and insert the portion of code below: def sfera(nome, rad): obj = DOC.addObject("Part::Sphere", nome) obj.Radius = rad DOC.recompute() return obj def mfuse_obj(nome, objs): obj = DOC.addObject("Part::MultiFuse", nome) obj.Shapes = objs obj.Refine = True DOC.recompute() return obj def aeroplano(): lung_fus = 30 diam_fus = 5 ap_alare = lung_fus * 1.75 larg_ali = 7.5 spess_ali = 1.5 alt_imp = diam_fus * 3.0 pos_ali = (lung_fus*0.70) off_ali = (pos_ali - (larg_ali * 0.5)) obj1 = base_cyl('primo cilindro', 360, diam_fus, lung_fus) obj2 = cubo('ali', ap_alare, spess_ali, larg_ali, True, off_ali) obj3 = sfera("naso", diam_fus) obj3.Placement = FreeCAD.Placement(Vector(0,0,lung_fus), FreeCAD.Rotation(0,0,0), Vector(0,0,0)) obj4 = cubo('impennaggio', spess_ali, alt_imp, larg_ali, False, 0) obj4.Placement = FreeCAD.Placement(Vector(0,alt_imp * -1,0), FreeCAD.Rotation(0,0,0), Vector(0,0,0)) objs = (obj1, obj2, obj3, obj4) obj = mfuse_obj("Forma esempio", objs) obj.Placement = FreeCAD.Placement(Vector(0,0,0), FreeCAD.Rotation(0,0,-90), Vector(0,0,pos_ali)) DOC.recompute() return obj # objects definition aeroplano() setview() Let's explain something in the code: We have used a method to define a sphere, using the most easy definition, using only the radius. We have introduced a second writing for the Union or Fusion, using multiple objects, not more distant from the usual Part::Fuse it uses Part:Multifuse. We only use one property Shapes. We have passed a tuple as arguments, but it accepts also a list. We have defined a complex object aeroplano (italian word for aeroplane), but we have done it in a "parametric" way, defining some parameters and deriving other parameters, through some calculation, based on the main parameters. We have used some Placement Placement poperties around in the method and before returning the final geometries we have used a Rotation property with the Yaw-Pitch-Roll writing. Note the last Vector(0,0, pos_ali), that define a center of rotation of the whole geometry.
aeroplane example aereo rotated Prop Placement
It can be easily noted that aeroplano geometry rotate around his "barycenter" or "center of gravity", that I've fixed at wing center, a place that is relatively "natural", but could be placed wherever you want. The first Vector(0,0,0) is the Translation vector, not used here, but if you substitute aeroplano() with these lines: obj_f = aeroplano() print(obj_F.Placement) You will see in the Report window this text: Placement [Pos=(0,-21,21), Yaw-Pitch-Roll=(0,0,-90)] What has happened? FreeCAD has translated the Vector(0,0,0), FreeCAD.Rotation(0,0,-90), Vector(0,0,pos_ali) in other word our Placement definition that specifies three components, Translation', Rotation and center of rotation in the "internal" values of only two components, Translation and Rotation. you can easily visualize the value of pos_ali using a print statement in the aeroplano(... method and see that it is: pos ali = 21.0 in other word the rotation center of the geometry is at Vector(0,0,21), but this rotation center is not shown in the GUI, it could be entered as a Placement value, it could not be easily retrieved. This is the meaning of the word "awkward" that I've used to define Placement property.


Topological data scripting

Introduction

Here we will explain to you how to control the Part module directly from the FreeCAD Python interpreter, or from any external script. Be sure to browse the Scripting section and the FreeCAD Scripting Basics pages if you need more information about how Python scripting works in FreeCAD. If you are new to Python, it is a good idea to first read the Introduction to Python.

See also

Part scripting OpenCASCADE

Class diagram

This is a Unified Modeling Language (UML) overview of the most important classes of the Part module:

Geometry

The geometric objects are the building blocks of all topological objects: Geom Base class of the geometric objects. Line A straight line in 3D, defined by starting point and end point. Circle Circle or circle segment defined by a center point and start and end point. Etc.

Topology

The following topological data types are available: Compound A group of any type of topological objects. Compsolid A composite solid is a set of solids connected by their faces. It expands the notions of WIRE and SHELL to solids. Solid A part of space limited by shells. It is three dimensional. Shell A set of faces connected by their edges. A shell can be open or closed. Face In 2D it is part of a plane; in 3D it is part of a surface. Its geometry is constrained (trimmed) by contours. It is two dimensional. Wire A set of edges connected by their vertices. It can be an open or closed contour depending on whether the edges are linked or not. Edge A topological element corresponding to a restrained curve. An edge is generally limited by vertices. It has one dimension. Vertex A topological element corresponding to a point. It has zero dimension. Shape A generic term covering all of the above.

Example: Create simple topology

We will now create a topology by constructing it out of simpler geometry. As a case study we will use a part as seen in the picture which consists of four vertices, two arcs and two lines.

Create geometry

First we create the distinct geometric parts of this wire. Making sure that parts that have to be connected later share the same vertices. So we create the points first: import Part from FreeCAD import Base V1 = Base.Vector(0, 10, 0) V2 = Base.Vector(30, 10, 0) V3 = Base.Vector(30, -10, 0) V4 = Base.Vector(0, -10, 0)

Arc


For each arc we need a helper point: VC1 = Base.Vector(-10, 0, 0) C1 = Part.Arc(V1, VC1, V4) VC2 = Base.Vector(40, 0, 0) C2 = Part.Arc(V2, VC2, V3)

Line


The line segments can be created from two points: L1 = Part.LineSegment(V1, V2) L2 = Part.LineSegment(V3, V4)

Put it all together

The last step is to put the geometric base elements together and bake a topological shape: S1 = Part.Shape([C1, L1, C2, L2])

Make a prism

Now extrude the wire in a direction and make an actual 3D shape: W = Part.Wire(S1.Edges) P = W.extrude(Base.Vector(0, 0, 10))

Show it all

Part.show(P)

Create basic shapes

You can easily create basic topological objects with the make...() methods from the Part module: b = Part.makeBox(100, 100, 100) Part.show(b) Some available make...() methods: makeBox(l, w, h, [p, d]) Makes a box located in p and pointing into the direction d with the dimensions (l,w,h). makeCircle(radius) Makes a circle with a given radius. makeCone(radius1, radius2, height) Makes a cone with the given radii and height. makeCylinder(radius, height) Makes a cylinder with a given radius and height. makeLine((x1, y1, z1), (x2, y2, z2)) Makes a line from two points. makePlane(length, width) Makes a plane with length and width. makePolygon(list) Makes a polygon from a list of points. makeSphere(radius) Makes a sphere with a given radius. makeTorus(radius1, radius2) Makes a torus with the given radii. See the Part API page for a complete list of available methods of the Part module.

Import modules

First we need to import the Part module so we can use its contents in Python. We'll also import the Base module from inside the FreeCAD module: import Part from FreeCAD import Base

Create a vector

Vectors are one of the most important pieces of information when building shapes. They usually contain three numbers (but not necessarily always): the X, Y and Z cartesian coordinates. You create a vector like this: myVector = Base.Vector(3, 2, 0) We just created a vector at coordinates X = 3, Y = 2, Z = 0. In the Part module, vectors are used everywhere. Part shapes also use another kind of point representation called Vertex which is simply a container for a vector. You access the vector of a vertex like this: myVertex = myShape.Vertexes[0] print(myVertex.Point) > Vector (3, 2, 0)

Create an edge

An edge is nothing but a line with two vertices: edge = Part.makeLine((0, 0, 0), (10, 0, 0)) edge.Vertexes > [<Vertex object at 01877430>, <Vertex object at 014888E0>] Note: You can also create an edge by passing two vectors: vec1 = Base.Vector(0, 0, 0) vec2 = Base.Vector(10, 0, 0) line = Part.LineSegment(vec1, vec2) edge = line.toShape() You can find the length and center of an edge like this: edge.Length > 10.0 edge.CenterOfMass > Vector (5, 0, 0)

Put the shape on screen

So far we created an edge object, but it doesn't appear anywhere on the screen. This is because the FreeCAD 3D scene only displays what you tell it to display. To do that, we use this simple method: Part.show(edge) The show function creates an object in our FreeCAD document and assigns our "edge" shape to it. Use this whenever it is time to display your creation on screen.

Create a wire

A wire is a multi-edge line and can be created from a list of edges or even a list of wires: edge1 = Part.makeLine((0, 0, 0), (10, 0, 0)) edge2 = Part.makeLine((10, 0, 0), (10, 10, 0)) wire1 = Part.Wire([edge1, edge2]) edge3 = Part.makeLine((10, 10, 0), (0, 10, 0)) edge4 = Part.makeLine((0, 10, 0), (0, 0, 0)) wire2 = Part.Wire([edge3, edge4]) wire3 = Part.Wire([wire1, wire2]) wire3.Edges > [<Edge object at 016695F8>, <Edge object at 0197AED8>, <Edge object at 01828B20>, <Edge object at 0190A788>] Part.show(wire3) Part.show(wire3) will display the 4 edges that compose our wire. Other useful information can be easily retrieved: wire3.Length > 40.0 wire3.CenterOfMass > Vector (5, 5, 0) wire3.isClosed() > True wire2.isClosed() > False

Create a face

Only faces created from closed wires will be valid. In this example, wire3 is a closed wire but wire2 is not (see above): face = Part.Face(wire3) face.Area > 99.99999999999999 face.CenterOfMass > Vector (5, 5, 0) face.Length > 40.0 face.isValid() > True sface = Part.Face(wire2) sface.isValid() > False Only faces will have an area, wires and edges do not.

Create a circle

A circle can be created like this: circle = Part.makeCircle(10) circle.Curve > Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1)) If you want to create it at a certain position and with a certain direction: ccircle = Part.makeCircle(10, Base.Vector(10, 0, 0), Base.Vector(1, 0, 0)) ccircle.Curve > Circle (Radius : 10, Position : (10, 0, 0), Direction : (1, 0, 0)) ccircle will be created at distance 10 from the X origin and will be facing outwards along the X axis. Note: makeCircle() only accepts Base.Vector() for the position and normal parameters, not tuples. You can also create part of the circle by giving a start and an end angle: from math import pi arc1 = Part.makeCircle(10, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 180) arc2 = Part.makeCircle(10, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 180, 360) Angles should be provided in degrees. If you have radians simply convert them using the formula: degrees = radians * 180/pi or by using Python's math module: import math degrees = math.degrees(radians)

Create an arc along points

Unfortunately there is no makeArc() function, but we have the Part.Arc() function to create an arc through three points. It creates an arc object joining the start point to the end point through the middle point. The arc object's toShape() function must be called to get an edge object, the same as when using Part.LineSegment instead of Part.makeLine. arc = Part.Arc(Base.Vector(0, 0, 0), Base.Vector(0, 5, 0), Base.Vector(5, 5, 0)) arc > <Arc object> arc_edge = arc.toShape() Part.show(arc_edge) Arc() only accepts Base.Vector() for points and not tuples. You can also obtain an arc by using a portion of a circle: from math import pi circle = Part.Circle(Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 10) arc = Part.Arc(circle,0,pi) Arcs are valid edges like lines, so they can be used in wires also.

Create a polygon

A polygon is simply a wire with multiple straight edges. The makePolygon() function takes a list of points and creates a wire through those points: lshape_wire = Part.makePolygon([Base.Vector(0, 5, 0), Base.Vector(0, 0, 0), Base.Vector(5, 0, 0)])

Create a bézier curve

Bézier curves are used to model smooth curves using a series of poles (points) and optional weights. The function below makes a Part.BezierCurve() from a series of FreeCAD.Vector() points. Note: when "getting" and "setting" a single pole or weight, indices start at 1, not 0. def makeBCurveEdge(Points): geomCurve = Part.BezierCurve() geomCurve.setPoles(Points) edge = Part.Edge(geomCurve) return(edge)

Create a plane

A Plane is a flat rectangular surface. The method used to create one is makePlane(length, width, [start_pnt, dir_normal]). By default start_pnt = Vector(0, 0, 0) and dir_normal = Vector(0, 0, 1). Using dir_normal = Vector(0, 0, 1) will create the plane facing in the positive Z axis direction, while dir_normal = Vector(1, 0, 0) will create the plane facing in the positive X axis direction: plane = Part.makePlane(2, 2) plane > <Face object at 028AF990> plane = Part.makePlane(2, 2, Base.Vector(3, 0, 0), Base.Vector(0, 1, 0)) plane.BoundBox > BoundBox (3, 0, 0, 5, 0, 2) BoundBox is a cuboid enclosing the plane with a diagonal starting at (3, 0, 0) and ending at (5, 0, 2). Here the BoundBox thickness along the Y axis is zero, since our shape is totally flat. Note: makePlane() only accepts Base.Vector() for start_pnt and dir_normal and not tuples.

Create an ellipse

There are several ways to create an ellipse: Part.Ellipse() Creates an ellipse with major radius 2 and minor radius 1 with the center at (0, 0, 0). Part.Ellipse(Ellipse) Creates a copy of the given ellipse. Part.Ellipse(S1, S2, Center) Creates an ellipse centered on the point Center, where the plane of the ellipse is defined by Center, S1 and S2, its major axis is defined by Center and S1, its major radius is the distance between Center and S1, and its minor radius is the distance between S2 and the major axis. Part.Ellipse(Center, MajorRadius, MinorRadius) Creates an ellipse with major and minor radii MajorRadius and MinorRadius, located in the plane defined by Center and the normal (0, 0, 1) eli = Part.Ellipse(Base.Vector(10, 0, 0), Base.Vector(0, 5, 0), Base.Vector(0, 0, 0)) Part.show(eli.toShape()) In the above code we have passed S1, S2 and center. Similar to Arc, Ellipse creates an ellipse object not an edge, so we need to convert it into an edge using toShape() for display. Note: Ellipse() only accepts Base.Vector() for points and not tuples. eli = Part.Ellipse(Base.Vector(0, 0, 0), 10, 5) Part.show(eli.toShape()) For the above Ellipse constructor we have passed center, MajorRadius and MinorRadius.

Create a torus

Using makeTorus(radius1, radius2, [pnt, dir, angle1, angle2, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = 0, angle2 = 360 and angle = 360. Consider a torus as small circle sweeping along a big circle. Radius1 is the radius of the big circle, radius2 is the radius of the small circle, pnt is the center of the torus and dir is the normal direction. angle1 and angle2 are angles in degrees for the small circle; the last angle parameter is to make a section of the torus: torus = Part.makeTorus(10, 2) The above code will create a torus with diameter 20 (radius 10) and thickness 4 (small circle radius 2) tor=Part.makeTorus(10, 5, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 180) The above code will create a slice of the torus. tor=Part.makeTorus(10, 5, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 360, 180) The above code will create a semi torus; only the last parameter is changed. i.e the remaining angles are defaults. Giving the angle 180 will create the torus from 0 to 180, that is, a half torus.

Create a box or cuboid

Using makeBox(length, width, height, [pnt, dir]). By default pnt = Vector(0, 0, 0) and dir = Vector(0, 0, 1). box = Part.makeBox(10, 10, 10) len(box.Vertexes) > 8

Create a sphere

Using makeSphere(radius, [pnt, dir, angle1, angle2, angle3]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = -90, angle2 = 90 and angle3 = 360. Angle1 and angle2 are the vertical minimum and maximum of the sphere, angle3 is the sphere diameter. sphere = Part.makeSphere(10) hemisphere = Part.makeSphere(10, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), -90, 90, 180)

Create a cylinder

Using makeCylinder(radius, height, [pnt, dir, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360. cylinder = Part.makeCylinder(5, 20) partCylinder = Part.makeCylinder(5, 20, Base.Vector(20, 0, 0), Base.Vector(0, 0, 1), 180)

Create a cone

Using makeCone(radius1, radius2, height, [pnt, dir, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360. cone = Part.makeCone(10, 0, 20) semicone = Part.makeCone(10, 0, 20, Base.Vector(20, 0, 0), Base.Vector(0, 0, 1), 180)

Modify shapes

There are several ways to modify shapes. Some are simple transformation operations such as moving or rotating shapes, others are more complex, such as unioning and subtracting one shape from another.

Transform operations

Translate a shape

Translating is the act of moving a shape from one place to another. Any shape (edge, face, cube, etc...) can be translated the same way: myShape = Part.makeBox(2, 2, 2) myShape.translate(Base.Vector(2, 0, 0)) This will move our shape "myShape" 2 units in the X direction.

Rotate a shape

To rotate a shape, you need to specify the rotation center, the axis, and the rotation angle: myShape.rotate(Base.Vector(0, 0, 0),Base.Vector(0, 0, 1), 180) The above code will rotate the shape 180 degrees around the Z Axis.

Matrix transformations

A matrix is a very convenient way to store transformations in the 3D world. In a single matrix, you can set translation, rotation and scaling values to be applied to an object. For example: myMat = Base.Matrix() myMat.move(Base.Vector(2, 0, 0)) myMat.rotateZ(math.pi/2) Note: FreeCAD matrixes work in radians. Also, almost all matrix operations that take a vector can also take three numbers, so these two lines do the same thing: myMat.move(2, 0, 0) myMat.move(Base.Vector(2, 0, 0)) Once our matrix is set, we can apply it to our shape. FreeCAD provides two methods for doing that: transformShape() and transformGeometry(). The difference is that with the first one, you are sure that no deformations will occur (see Scaling a shape below). We can apply our transformation like this: myShape.transformShape(myMat) or myShape.transformGeometry(myMat)

Scale a shape

Scaling a shape is a more dangerous operation because, unlike translation or rotation, scaling non-uniformly (with different values for X, Y and Z) can modify the structure of the shape. For example, scaling a circle with a higher value horizontally than vertically will transform it into an ellipse, which behaves mathematically very differently. For scaling, we cannot use the transformShape(), we must use transformGeometry(): myMat = Base.Matrix() myMat.scale(2, 1, 1) myShape=myShape.transformGeometry(myMat)

Boolean operations

Subtraction

Subtracting a shape from another one is called "cut" in FreeCAD and is done like this: cylinder = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0)) sphere = Part.makeSphere(5, Base.Vector(5, 0, 0)) diff = cylinder.cut(sphere)

Intersection

The same way, the intersection between two shapes is called "common" and is done this way: cylinder1 = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0)) cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1)) common = cylinder1.common(cylinder2)

Union

Union is called "fuse" and works the same way: cylinder1 = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0)) cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1)) fuse = cylinder1.fuse(cylinder2)

Section

A "section" is the intersection between a solid shape and a plane shape. It will return an intersection curve, a compound curve composed of edges. cylinder1 = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0)) cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1)) section = cylinder1.section(cylinder2) section.Wires > [] section.Edges > [<Edge object at 0D87CFE8>, <Edge object at 019564F8>, <Edge object at 0D998458>, <Edge object at 0D86DE18>, <Edge object at 0D9B8E80>, <Edge object at 012A3640>, <Edge object at 0D8F4BB0>]

Extrusion

Extrusion is the act of "pushing" a flat shape in a certain direction, resulting in a solid body. Think of a circle becoming a tube by "pushing it out": circle = Part.makeCircle(10) tube = circle.extrude(Base.Vector(0, 0, 2)) If your circle is hollow, you will obtain a hollow tube. If your circle is actually a disc with a filled face, you will obtain a solid cylinder: wire = Part.Wire(circle) disc = Part.Face(wire) cylinder = disc.extrude(Base.Vector(0, 0, 2))

Explore shapes

You can easily explore the topological data structure: import Part b = Part.makeBox(100, 100, 100) b.Wires w = b.Wires[0] w w.Wires w.Vertexes Part.show(w) w.Edges e = w.Edges[0] e.Vertexes v = e.Vertexes[0] v.Point By typing the lines above in the Python interpreter, you will gain a good understanding of the structure of Part objects. Here, our makeBox() command created a solid shape. This solid, like all Part solids, contains faces. Faces always contain wires, which are lists of edges that border the face. Each face has at least one closed wire (it can have more if the face has a hole). In the wire, we can look at each edge separately, and inside each edge, we can see the vertices. Straight edges have only two vertices, obviously.

Edge analysis

In case of an edge, which is an arbitrary curve, it's most likely you want to do a discretization. In FreeCAD the edges are parametrized by their lengths. That means you can walk an edge/curve by its length: import Part box = Part.makeBox(100, 100, 100) anEdge = box.Edges[0] print(anEdge.Length) Now you can access a lot of properties of the edge by using the length as a position. That means if the edge is 100mm long the start position is 0 and the end position 100. anEdge.tangentAt(0.0) # tangent direction at the beginning anEdge.valueAt(0.0) # Point at the beginning anEdge.valueAt(100.0) # Point at the end of the edge anEdge.derivative1At(50.0) # first derivative of the curve in the middle anEdge.derivative2At(50.0) # second derivative of the curve in the middle anEdge.derivative3At(50.0) # third derivative of the curve in the middle anEdge.centerOfCurvatureAt(50) # center of the curvature for that position anEdge.curvatureAt(50.0) # the curvature anEdge.normalAt(50) # normal vector at that position (if defined)

Use a selection

Here we see now how we can use a selection the user did in the viewer. First of all we create a box and show it in the viewer. import Part Part.show(Part.makeBox(100, 100, 100)) Gui.SendMsgToActiveView("ViewFit") Now select some faces or edges. With this script you can iterate over all selected objects and their sub elements: for o in Gui.Selection.getSelectionEx(): print(o.ObjectName) for s in o.SubElementNames: print("name: ", s) for s in o.SubObjects: print("object: ", s) Select some edges and this script will calculate the length: length = 0.0 for o in Gui.Selection.getSelectionEx(): for s in o.SubObjects: length += s.Length print("Length of the selected edges: ", length)

Example: The OCC bottle

A typical example found on the OpenCasCade Technology website is how to build a bottle. This is a good exercise for FreeCAD too. In fact, if you follow our example below and the OCC page simultaneously, you will see how well OCC structures are implemented in FreeCAD. The script is included in the FreeCAD installation (inside the Mod/Part folder) and can be called from the Python interpreter by typing: import Part import MakeBottle bottle = MakeBottle.makeBottle() Part.show(bottle)

The script

For the purpose of this tutorial we will consider a reduced version of the script. In this version the bottle will not be hollowed out, and the neck of the bottle will not be threaded. import Part, math from FreeCAD import Base def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0): aPnt1=Base.Vector(-myWidth / 2., 0, 0) aPnt2=Base.Vector(-myWidth / 2., -myThickness / 4., 0) aPnt3=Base.Vector(0, -myThickness / 2., 0) aPnt4=Base.Vector(myWidth / 2., -myThickness / 4., 0) aPnt5=Base.Vector(myWidth / 2., 0, 0) aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4) aSegment1=Part.LineSegment(aPnt1, aPnt2) aSegment2=Part.LineSegment(aPnt4, aPnt5) aEdge1=aSegment1.toShape() aEdge2=aArcOfCircle.toShape() aEdge3=aSegment2.toShape() aWire=Part.Wire([aEdge1, aEdge2, aEdge3]) aTrsf=Base.Matrix() aTrsf.rotateZ(math.pi) # rotate around the z-axis aMirroredWire=aWire.copy() aMirroredWire.transformShape(aTrsf) myWireProfile=Part.Wire([aWire, aMirroredWire]) myFaceProfile=Part.Face(myWireProfile) aPrismVec=Base.Vector(0, 0, myHeight) myBody=myFaceProfile.extrude(aPrismVec) myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges) neckLocation=Base.Vector(0, 0, myHeight) neckNormal=Base.Vector(0, 0, 1) myNeckRadius = myThickness / 4. myNeckHeight = myHeight / 10. myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal) myBody = myBody.fuse(myNeck) return myBody el = makeBottleTut() Part.show(el)

Detailed explanation

import Part, math from FreeCAD import Base We will need, of course, the Part module, but also the FreeCAD.Base module, which contains basic FreeCAD structures like vectors and matrices. def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0): aPnt1=Base.Vector(-myWidth / 2., 0, 0) aPnt2=Base.Vector(-myWidth / 2., -myThickness / 4., 0) aPnt3=Base.Vector(0, -myThickness / 2., 0) aPnt4=Base.Vector(myWidth / 2., -myThickness / 4., 0) aPnt5=Base.Vector(myWidth / 2., 0, 0) Here we define our makeBottleTut function. This function can be called without arguments, like we did above, in which case default values for width, height, and thickness will be used. Then, we define a couple of points that will be used for building our base profile. ... aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4) aSegment1=Part.LineSegment(aPnt1, aPnt2) aSegment2=Part.LineSegment(aPnt4, aPnt5) Here we define the geometry: an arc, made of three points, and two line segments, made of two points. ... aEdge1=aSegment1.toShape() aEdge2=aArcOfCircle.toShape() aEdge3=aSegment2.toShape() aWire=Part.Wire([aEdge1, aEdge2, aEdge3]) Remember the difference between geometry and shapes? Here we build shapes out of our construction geometry. Three edges (edges can be straight or curved), then a wire made of those three edges. ... aTrsf=Base.Matrix() aTrsf.rotateZ(math.pi) # rotate around the z-axis aMirroredWire=aWire.copy() aMirroredWire.transformShape(aTrsf) myWireProfile=Part.Wire([aWire, aMirroredWire]) So far we have built only a half profile. Instead of building the whole profile the same way, we can just mirror what we did and glue both halves together. We first create a matrix. A matrix is a very common way to apply transformations to objects in the 3D world, since it can contain in one structure all basic transformations that 3D objects can undergo (move, rotate and scale). After we create the matrix we mirror it, then we create a copy of our wire and apply the transformation matrix to it. We now have two wires, and we can make a third wire out of them, since wires are actually lists of edges. ... myFaceProfile=Part.Face(myWireProfile) aPrismVec=Base.Vector(0, 0, myHeight) myBody=myFaceProfile.extrude(aPrismVec) myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges) Now that we have a closed wire, it can be turned into a face. Once we have a face, we can extrude it. In doing so, we make a solid. Then we apply a nice little fillet to our object because we care about good design, don't we? ... neckLocation=Base.Vector(0, 0, myHeight) neckNormal=Base.Vector(0, 0, 1) myNeckRadius = myThickness / 4. myNeckHeight = myHeight / 10. myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal) At this point, the body of our bottle is made, but we still need to create a neck. So we make a new solid, with a cylinder. ... myBody = myBody.fuse(myNeck) The fuse operation is very powerful. It will take care of gluing what needs to be glued and remove parts that need to be removed. ... return myBody Then, we return our Part solid as the result of our function. el = makeBottleTut() Part.show(el) Finally, we call the function to actually create the part, then make it visible.

Example: Pierced box

Here is a complete example of building a pierced box. The construction is done one side at a time. When the cube is finished, it is hollowed out by cutting a cylinder through it. import Part, math from FreeCAD import Base size = 10 poly = Part.makePolygon([(0, 0, 0), (size, 0, 0), (size, 0, size), (0, 0, size), (0, 0, 0)]) face1 = Part.Face(poly) face2 = Part.Face(poly) face3 = Part.Face(poly) face4 = Part.Face(poly) face5 = Part.Face(poly) face6 = Part.Face(poly) myMat = Base.Matrix() myMat.rotateZ(math.pi / 2) face2.transformShape(myMat) face2.translate(Base.Vector(size, 0, 0)) myMat.rotateZ(math.pi / 2) face3.transformShape(myMat) face3.translate(Base.Vector(size, size, 0)) myMat.rotateZ(math.pi / 2) face4.transformShape(myMat) face4.translate(Base.Vector(0, size, 0)) myMat = Base.Matrix() myMat.rotateX(-math.pi / 2) face5.transformShape(myMat) face6.transformShape(myMat) face6.translate(Base.Vector(0, 0, size)) myShell = Part.makeShell([face1, face2, face3, face4, face5, face6]) mySolid = Part.makeSolid(myShell) myCyl = Part.makeCylinder(2, 20) myCyl.translate(Base.Vector(size / 2, size / 2, 0)) cut_part = mySolid.cut(myCyl) Part.show(cut_part)

Loading and saving

There are several ways to save your work. You can of course save your FreeCAD document, but you can also save Part objects directly to common CAD formats, such as BREP, IGS, STEP and STL. Saving a shape to a file is easy. There are exportBrep(), exportIges(), exportStep() and exportStl() methods available for all shape objects. So, doing: import Part s = Part.makeBox(10, 10, 10) s.exportStep("test.stp") will save our box into a STEP file. To load a BREP, IGES or STEP file: import Part s = Part.Shape() s.read("test.stp") To convert a STEP file to an IGS file: import Part s = Part.Shape() s.read("file.stp") # incoming file igs, stp, stl, brep s.exportIges("file.igs") # outbound file igs


Creating a simple part with PartDesign

This tutorial aims to teach FreeCAD beginners a few basic features through an example. After covering the basics in the User hub, you will be able to model a first part step by step. We will cover in this tutorial in particular: Using Part Design workbench, tracing the sketch. Using Pad and Pocket features. Changing color and transparency. Moving the part manually. Displaying reference dimensions in the sketch. Editing one or more dimensions. Using external geometry feature and using a reference plane to centre a hole.

Using Part Design workbench, tracing the sketch

Create a new document and switch to the Part Design workbench using either the workbench selector (labelled 10 in the linked image) or by going to the View → Workbench menu. FreeCAD will start with toolbars at the top, the combo view to the left and the 3D view at the right. Create body: Press Create body. Note: do not confuse the Body, which icon is blue, with the Part container which icon is yellow. In the Model tab under the Combo View sidebar, a new object labelled "Body" appears under the document label, which is currently "Unnamed" since we haven't saved our document yet. The Body is a container in which Part Design features are sequentially arranged to form a single solid. It contains its own reference axes and planes. It will be highlighted in light blue in the Model tree, which means that it is active, that is to say that we can edit the elements it contains as well as add new elements to it. If it's not highlighted, double-click it or right-click and select Toggle active body in the contextual menu. In front of the Body label, there is a blue icon identical to the one above, and an arrow or a plus sign, depending on your operating system. Clicking on the arrow or plus sign in front of Body expands its content. At this point, it only contains an element labelled Origin. In front of this Origin is also an arrow or plus sign. Click on it to expand its content. It reveals the aforementioned reference axes and planes as shown in the image below: The newly created active Body with its content expanded. The Origin is greyed out, which indicates that its content is not visible in the 3D view. You can make Origin's content visible in the 3D view by selecting Origin and pressing the spacebar on your keyboard. Origin will now show black in the tree. Press the spacebar again to hide its content in the 3D view. Click again on the arrow or plus sign in front of Origin to collapse its content in the Model tree. Before we continue, let's take the opportunity to rename the Body. Rename body: In the Model tree, click on the Body with the right mouse button. Select Rename and type a name, for example "Body part1" and press Enter to validate. Create sketch: We will now trace the sketch which defines the general shape of the part. A sketch is a diagram describing a profile to be applied to a feature in order to produce a shape. It can be either "positive" or "additive", like a pad for example; or "negative" or "subtractive", like a pocket. Here, since the part's general shape is regular along the Y axis, we will create the Pad along this axis. Press New sketch. The Combo View now switches to the Tasks tab and displays the Select feature dialog. This dialog expects the selection of a plane to which to attach our sketch, and lists the available planes. Select XZ_Plane (Base plane) and press OK. The interface now changes, the Sketcher now takes over and its toolbars appear above the 3D view. We find ourselves on the XZ plane of the body to trace the sketch. To aid with sketching, set the following options in "Edit controls" in the Tasks panel to the left: Show grid: checked Grid size: 10 mm Auto constraints: checked We will trace the following sketch: Let's start with the first segments: Select the Line tool. Click on the origin point, first making sure that a small red dot appears besides and to the right of the mouse pointer. Click next on the X axis about 10 squares to the right or at about 100 mm. If the segment is not exactly 100 mm at this point, it does not matter, we will later give it a fixed dimension that will constrain this length. Do the same for the other segments, try to aim at the points that you have created which must light up in yellow. Which means that these points will be coincident. You should get pretty much this: Note the small red lines above and beside the segments you have drawn: these are horizontal and vertical constraints. Your lines are forced to stay either horizontal or vertical. Note also the symbol in the form of a small arc on the left: it means that the point is fixed to the Z axis. Now pick different line segments with the left mouse button and while keeping the left button pressed, drag the mouse to try to move them: some are free, others not. Applying constraints: At the top of the combo box, in the Tasks panel, you can read the number of degrees of freedom of the already sketched elements: it must be about 6, the objective of the constraints is to reduce the number of degrees of freedom to 0. The slanted line should be free to rotate at this time: we will give it an angle constraint to fix it. Click on the slanted line, then the bottom line; once selected these lines will turn dark green; then click the Constrain internal angle icon. Enter a value of 30°. Both lines have a fixed angle now. The constraint was created to the left of the sketch; with the mouse, move it inside the profile. We will now constrain the bottom line with a dimension: select it then click on Constrain horizontal distance. Enter a value of 100 mm. The vertical line on the right now aligns exactly with the grid's 10th square to the right of the origin. Let's set the overall height to the profile by selecting the highest point on the left then the origin point. Click on constrain vertical distance, enter a value of 50 mm. Do the same for the horizontal length of the sloped line with another 50 mm horizontal distance constraint. Move the dimensions away from the profile for better visibility. You should now have something like this: Notice that the number of degrees of freedom reduced to 2. These are the ends still open. Tracing the arc Click on Arc, position the center at approximately x = 80 y = 30; then click to define the first starting point of the arc on the upper horizontal line's right end point; then click to define the end of the arc to the right vertical line's upper end point (make sure the points are highlighted in yellow before clicking). Give the radius a radius constraint: select the arc, then click on Constrain radius then enter a value of 20 mm. Now let's make the arc tangent to the lines it's connected to: select the arc, then the top line, then click on Constrain tangent. A Constraint substitution message appears, click OK. Do the same for the tangent constraint on the other side of the arc. We proceeded in two stages to create the sketch, but we could also have traced the profile completely before constraining it fully.
Fully constrained sketch: If you worked well, you should get this: The sketch has become green, which means that it is fully constrained. There is no longer any ambiguity, everything is perfectly defined. This is confirmed by the solver message at the top left. Also note that the center of the arc has moved slightly, indeed giving these last three constraints, FreeCAD has calculated the true position of the center. If your sketch is not yet green, one or more points are not coincident (2 points can be superimposed yet not be coincident). Make a small window (capture window) around a point to select, and create a Coincident constraint. Note: don't mistake the Coincident constraint for the Sketcher Point; while their icons are very similar, the latter has a larger icon; it adds a lone point in the sketch. Proceed in the same way with all the points. If your sketch is still not green, verify that all lines (but the slanted one) have either a Vertical constraint, and add if necessary.

Using Pad and Pocket features

Click on Close in the Tasks tab, at the top left corner. We automatically exit the Sketcher workbench, and the Part Design workbench is activated again. The Combo View switches back to the Model tab. If you left your Body part1 expanded, you will see a new Sketch element below Origin, and nested under the Body. At this point, let's save our document. Give it a name (for example "tutorial1", or any name that you find relevant). It is good practice to save your document often, for example after completing a sketch or a feature. Click on Isometric view then Fit all, which gives a centered 3D isometric view. Click on Pad, enter a length of 30 mm. Click OK, the shape is completed. In the Model tree, a Pad object (that we call feature) appears instead of the Sketch. In fact, it has claimed Sketch, since it is based on it; clicking on the arrow or plus sign in front of Pad to expand it will reveal the Sketch underneath, which was automatically made hidden (its label is grayed out). Note that the shape created forms a solid. Creating the hole Click on the top (square) side of the part and click the icon to create a new sketch. FreeCAD creates a new sketch attached to this face. So we are on a plane parallel to the absolute plane XY, but offset in height from the height of the piece, i.e. 50 mm. You can switch the 3D window to an isometric view or stay in top view . At any time, you can return to Sketch view (the view is oriented to face the sketch plane) using the Sketcher ViewSketch icon. Note that the origin of this new sketch is that of the body. They may be different, but here are confounded with the absolute origin. With the Circle tool, click roughly in the center of the face and make a circle of any radius. Select the circle then create a Radius constraint, enter a value of 5 mm. Select the center of the circle then create a Lock constraint; double-click on the horizontal dimension and enter -65 mm (here we indicate a position relative to the origin of the sketch). Do the same for the vertical dimension (-15 mm). The circle takes its correct position and the sketch becomes green, indicating it is fully constrained: Close the sketch; in the Model tree, a new Sketch001 object has appeared below Pad. While Sketch001 is still selected, click on Pocket. Pocket is a feature called "subtractive", it removes material from our part, here in the form of a cylinder since the sketch is a circle. Set "Through all" to completely cut the part. Press OK to complete. In the Model tree, a new element labelled Pocket appears at the bottom of the Body part1, and claims Sketch001.

Changing color and transparency

It is possible to change the color of the part, it is often useful to distinguish a part among others. The transparency of the piece can also be modified, which is useful for visualizing its internals. Select the Body part1 body; make sure that the Model tab of the Combo View is selected and go to the lower part of the Combo View, then click on the View tab; locate the Shape Color property; you may need to use the vertical scroll bar to the right to find it. You can also widen the Property column: hover your mouse pointer over the separating line between the Property and Value headers; when the pointer turns into a double-sided arrow, press and hold your left mouse button and drag sideways, then release. In the right column, click on the gray square, which opens the Select Color dialog. Pick another color then click OK. Next, again in the View tab, change the value of Transparency, for example to 50 and press Enter to complete (0 = totally opaque, 100 = totally transparent). The hole is now visible inside the part. This is often useful for seeing the hidden or internal faces of the model. You can also vary "Line Color" and "Line Width" to change the line thickness and the color of the part outline.

Manually move the part

Go to the View menu and select Toggle axis cross. These are the absolute axes. You should see in the 3D view, the 3 axes X, Y, Z in red, green and blue. This landmark will help us to orient ourselves in space. This landmark is fixed and immutable, it is either the view that rotates or the object that rotates in this space. Select the Body; at the bottom of the Combo View on the left, you can see this (the Data tab needs to be on the foreground, you may need to click on the Data tab to make it visible): Click on the three small dots, i.e., the ellipsis (if they don't appear, click on the Value section of the Placement field); this opens a new dialog in the Tasks panel. Using the arrows you can vary the position and angles of the part. It is actually the position of the body (so its origin) that moves in space, the orientation of the 3D view does not change. Another method: in the Combo View, select the Body and click on the right button of the mouse, then select Transform. A view like this appears: Hold and drag the cones along the axes or the spheres to move the body in all directions. Validate. Then reset angles and coordinates to 0.

Displaying reference dimensions in the sketch

It may be useful to know the dimensions of some parts of the sketch, from the internal calculation of FreeCAD. It can be used just for reference, or use them later to set other dimensions for example. In the Model tree, if necessary expand Body part1 then Pad to show the first Sketch. Double-click on it (or right-click and select Edit sketch in the contextual menu) then click on Toggle Constraint. (Note: depending on your computer display resolution, this icon may not be visible. At the right end of the Constraints toolbar, you may find a » button. Click on it to expand and access collapsed icons.) From now on, we can create reference dimensions rather than dimensional constraints: they will be blue and will have no influence on the shapes of the sketch from which they come, they are calculated automatically. You can display these dimensions for example: We can see for example that the arc has a length of 20 since it's tangent with the edges. We can also see that FreeCAD calculates the left face (50-50xTAN 30 °), as well as the distance dimension of the axis of the arc with the origin.

Editing one or more dimensions

During modeling, you can vary the dimensions of the model. It's very simple: for the thickness of the piece, double-click Pad, then enter a new value, 40mm for example. In the lower part of the combo view, you can change this value as well. Validate, the shape of the object has changed. Do the same for the total length of the piece: double-click on Sketch, then double-click on the 100 mm dimensional constraint, change it to 110 mm then validate. We can see that the piece was enlarged, but the hole is no longer centered in the middle of the top face. That's because it has been constrained to the sketch origin. Which does not necessarily correspond to what one would like, the hole should remain in the center, whatever the size of the face.

Center the hole

First method using external geometry. Edit again the sketch of the hole and erase its horizontal and vertical distance constraints. Then click on External Geometry. We will now create two lines in the sketch, but extracted from a shape (or feature) external to this one and previously defined: that of the Pad. Click on a vertical edge at the top of the part. For example, the edge slope side. A new magenta line will appear above the edge. Repeat for the other edge, on the rounded side. We can now use these lines (and especially their end points) to centre the circle, however we must add two construction lines: for example the diagonals. Click on Construction Mode, we switch to construction mode: the lines will be blue and will be discarded outside of the sketch editing mode. They will allow to fix the center of the circle. Create the diagonals in the same way that you drew the first lines. Make sure all points are coincident. Then select the center of the circle, then the two blue diagonal lines and click on Point on object, the circle must be centred at the intersection of the diagonals, that is at the center of the face. The sketch must be green, completely constrained (it is essential). Note that besides the radius of the circle, it is no longer necessary to create dimensional constraints. Please note that in addition to switching the the toolbar to construction mode, the Construction Mode button can also switch individual Sketcher elements to construction mode if they have been selected. If you accidentally switch an element to construction mode, you may get an error when you exit the sketch. Leave the sketch, we see that the circle is well centred. (The pocket feature was not deleted, but modified). If you change the dimensions of the part again, the thickness or the length, the circle will remain centered on the face. Avoid construction lines: It is often possible to avoid creating construction lines. You can edit the sketch again, erase the construction lines and use a Symmetric constraint between the two opposite vertices of the external geometry lines and the centre of the circle (select points in this order): We get exactly the same result for the position of the hole. In fact, thanks to the constraints available in the Sketcher workbench, there are many possible methods. This example shows that it is often better to choose the simplest method, thus limiting the number of objects created as well as the errors that might result. Second method using a datum plane. Here is another, faster method that is possible since version 0.17: the use of a datum plane and its attachment. Start by erasing the "Pocket" function as well as the sketch of the hole. Select the top face and click Datum point: create a datum point in the active body. The attachment mode chosen must be "Center of mass". As the face is rectangular, its center of mass corresponds to the center of its diagonals. Validate, and a datum point is created. Select the top face again and while holding down the CTRL key, select the point you just created in the Model tree, release CTRL and click Datum plane. A reference plane is created with the origin of the point. Click OK. It is now very easy to center the circle! Select from the Model tree or in the 3D view the plane you created, and click on Create a sketch, a sketch is created with as origin, the origin of the plane. Then just trace the 5 mm radius circle on this origin, then validate (the sketch must be green imperatively). You get with "Pocket", as created previously, the hole and it will always be centered. This tutorial is completed, save this file, you can have fun exploring various features. Change other dimensions, make other shapes, put other holes on other faces, it is when making mistakes that we progress!